邮递员 GET 请求有效,但 Ajax CORS 无效

Posted

技术标签:

【中文标题】邮递员 GET 请求有效,但 Ajax CORS 无效【英文标题】:Postman GET request works but not Ajax CORS 【发布时间】:2018-03-29 14:53:12 【问题描述】:

我正在尝试发出 AJAX 请求以获取 restAPI 的信息。

如果我使用 POSTMAN 对其进行测试,它也适用于 Putty,此代码选择 RAW,但由于 CORS 问题,不适用于 AJAX。

这是适用于 Putty 的代码(它返回 JSON 数据):

GET /api/slot/0/io/do HTTP/1.1\r\n
Host: 172.25.0.208\r\n
Content-Type: application/json\r\n
Accept: vdn.dac.v1\r\n
\r\n

这是 jQuery AJAX 代码:

//Build GET Request URL
var url = "//" + ipDevice + "/api/slot/" + slot + "/io/do";
jQuery.support.cors = true;
//GET Request with HTTP header info
$.ajax(
    "url": url,
    "method": "GET",
    "headers": 
        "Accept": "vdn.dac.v1",
        "Content-type": "application/json"
    ,
    "success": function (response) 
        getPowerStatusSuccess(response);
    ,
    "error": function (response) 
        getPowerStatusFail(response);
    
);

我在浏览器控制台 (Firefox) 上遇到的错误是:

【问题讨论】:

Why does my javascript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?的可能重复 【参考方案1】:

您的 api 需要返回一个 cors 标头 ~allow-origin 设置为 * 或域白名单。

access-control-allow-origin: *

【讨论】:

感谢您的回答,但它不是我的 API,所以我无法添加此标头。

以上是关于邮递员 GET 请求有效,但 Ajax CORS 无效的主要内容,如果未能解决你的问题,请参考以下文章

如何在从 jquery 发送 $.get 请求时启用 CORS?

CORS 正在阻止 PUT、DELETE 和 POST 请求,但 GET 正在工作

GET 请求在邮递员中有效,但在 Axios 中失败

使用 NancyFX 获取在 CORS 中不起作用的请求

CORS - 带有“授权”的 Ajax 或 XMLHttpRequest 类型 GET 获取错误 307

使用 axios 从 react js 调用 Spring Boot get 方法时,浏览器显示“请求已被 CORS 策略阻止”