Why is adding an extra header making the AJAX call

2020-04-27 00:08发布

问题:

AJAX call:

$.ajax({
    url: "http://myserver2:296/api/Demo/HelloWorld",
    type: "GET",
    dataType: 'JSONP',
    jsonp: "callback",
    headers: { 'API_KEY': 'mykey09090' },
    success: function (result) {
        console.log(result);
    },
    error: ajaxFailed
});

function ajaxFailed(xmlRequest) {
    alert(xmlRequest.status + ' \n\r ' +
          xmlRequest.statusText + '\n\r' +
          xmlRequest.responseText);
}

I get the following error: Failed to load resource: the server responded with a status of 403 (Forbidden). However when I use Postman, I just have to add the headers with the http://myserver2:296/api/Demo/HelloWorld url it returns the string.

Can I please get some assistance to resolve the issue.

My goal, is to allow the origin server along with the API key correctly provided to get the data back from the Web Api.

回答1:

Adding the API_KEY header to the request triggers your browser to first send a CORS preflight OPTIONS request. Any headers you add to a request other than headers defined as CORS-safelisted request-headers will trigger your browser to send a CORS preflight OPTIONS request.

I can’t tell for sure but it seems like the 403 you’re seeing is from your server responding to that OPTIONS request, and saying it doesn’t expect to get OPTIONS requests and doesn’t allow them.

The reason you don’t get this from Postman is that unlike browser engines, Postman does not implement CORS, so it does not send the OPTIONS request. (Postman does not operate under the same-origin Web-security model that browsers enforce for Web applications.)

So to make your client app work as expected for scripted cross-origin access to that server, you must configure the server to respond in the right way to that CORS preflight OPTIONS request.