Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set headers to $.get() or $.post() function

How do I add authorization headers to the following ajax request?

$.get(urlAPI + "/api/account/get", function (data) {
                    alert(data);
                }, 'json');
like image 231
Erick D. Machado Alvarez Avatar asked Jun 13 '17 15:06

Erick D. Machado Alvarez


People also ask

How do you put a header in a GET request?

In the Name field, enter the name of your header rule (for example, My header ). From the Type menu, select Request, and from the Action menu, select Set. In the Destination field, enter the name of the header affected by the selected action. In the Source field, enter where the content for the header comes from.

Can we send headers in GET request?

For example, to send a GET request with a custom header name, you can use the "X-Real-IP" header, which defines the client's IP address. For a load balancer service, "client" is the last remote host. Your load balancer intercepts traffic between the client and your server.

How do you set a header?

Go to Insert > Header or Footer. Choose from a list of standard headers or footers, go to the list of Header or Footer options, and select the header or footer that you want. Or, create your own header or footer by selecting Edit Header or Edit Footer. When you're done, select Close Header and Footer or press Esc.

How do I pass headers to Axios post?

When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization .


3 Answers

You can define ajaxsetup before your request $ .get () to include the authorization in the header

$.ajaxSetup({
   headers:{
      'Authorization': "auth username and password"
   }
});

$.get(urlAPI + "/api/account/get", function (data) {
    alert(data);
}, 'json');
like image 142
Luis Angel Meza Perez Avatar answered Oct 13 '22 19:10

Luis Angel Meza Perez


based on jquery page $.get() document from version 1.12 there is a settings option to pass the base settings to the method.

jQuery.get( [settings ] )

or

$.get( [settings] )

settings is a plain object so you can use it like

{ 
  url: 'http://requesturl.io', 
  data: {},
  headers: { 'your-custom-header': 'custom-header-value' }
}
like image 33
MRebati Avatar answered Oct 13 '22 18:10

MRebati


$.ajax({
  url: 'foo/bar',
  headers: { 'x-my-custom-header': 'some value' }
});
like image 29
Prashanth Reddy Avatar answered Oct 13 '22 18:10

Prashanth Reddy