为什么要添加额外的头使AJAX调用失败 [英] Why is adding an extra header making the AJAX call fail

查看:53
本文介绍了为什么要添加额外的头使AJAX调用失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AJAX调用:

$.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);
}

我收到以下错误:加载资源失败:服务器的响应状态为403(禁止)。但是,当我使用Postman时,只需要在 http:// myserver2:296 / api / Demo / HelloWorld 网址中添加标头即可返回字符串。

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.

我的目标是允许原始服务器与正确提供了API密钥以从Web Api取回数据。

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

推荐答案

添加 API_KEY 请求标头触发浏览器首先发送CORS飞行前选项请求。您添加到请求中的任何标头,而不是定义为 CORS安全列出的请求标头将触发您的浏览器发送CORS飞行前选项请求。

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.

我不确定,但似乎您看到的403是来自服务器响应该OPTIONS请求,并说它不希望收到OPTIONS请求并且不允许它们。

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.

您没有从Postman获得此信息的原因是,与浏览器引擎不同,Postman没有实现CORS,因此它不会发送OPTIONS请求。 (Postman不在浏览器为Web应用程序实施的相同来源的Web安全模型下运行。)

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.)

因此,请确保您的客户端应用程序可以按脚本执行跨脚本操作,原始访问该服务器,则必须将服务器配置为以正确的方式响应CORS预检OPTIONS请求。

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.

这篇关于为什么要添加额外的头使AJAX调用失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆