Can I set headers in json requests for cross domain?

I did some research on the Internet, but I was not able to get a complete picture of this topic. Can someone help solve this answer now and forever?

This is what I have found so far:

  • You can cross-call a domain using jsonp. Changing headers in jsonp call is never allowed
  • You can cross-call a domain using json if the server allows it.

This is what I am trying to do:

$.ajax({ type: "GET", crossDomain: true, beforeSend: function (request) { request.setRequestHeader("Authorization", "Bearer " + ($("#accesstoken").val())); }, contentType: "application/json; charset=utf-8", url: myJSonServer + encodeURI(operation), dataType: 'json', cache: false, success: callback, error: function (jqXhr, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown); } }); 

This is what happens:

  • When myJSonServer is in the same domain, no problem at all
  • When myJSonServer is in a different domain, the request is sent, but without a Bearer header

This carrier header is part of the oAuth2 standard.

I know that maybe this is not the best solution setting accessToken in the browser. And I know that I can use a proxy server for this situation.

I'm just wondering if it is or will it be possible to set headers for a json cross-domain request?
Thanks

- solved the problem

I used MVC4 and added crossDomainScriptAccessEnabled = "true" in web.config. I thought that would be enough, but the response of the upsillers solved my problem. I added this to my web.config:

  <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Authorization" /> </customHeaders> </httpProtocol> </system.webServer> 
+7
source share
3 answers

With JSONP, setting custom headers is not possible.

In CORS, the server must send an Access-Control-Allow-Headers header to allow users unusual request headers. On the HTML5 Rocks CORS page:

Access-Control-Allow-Headers ... - A list of supported request headers, separated by commas.

Therefore, your server must send Access-Control-Allow-Headers: Authorization so that the browser knows that it is allowed to send Authorization to the server with the request. Without this header, the browser will send only a few common headers with the request and ignore the rest.

+10
source

Since jsonp works by creating a script tag and using the src= attribute to load a resource from another domain. So I don’t think there is a way to change the request headers.

+1
source

If you use JSONP to create a cross origin request, then the answer is no, you cannot set HTTP headers for such requests. If you use CORS to create cross-origin queries, then the answer is yes, since you are using simple XHR to query: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing .

0
source

All Articles