我无法使用request-promise从我的react应用发出GET请求。这是我在Chrome中遇到的错误。我正在向ServiceNow发出GET请求。
Access to fetch at 'omitted' from
origin 'omitted' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No 'Access-Control-Allow- Origin'
header is present on the requested resource. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the resource
with CORS disabled.
这是我通过选项的地方
export const getOptions = URL => {
return {
method: "GET",
uri: URL,
proxy: "omitted",
auth: { user: "omitted", pass: "omitted" },
json: true
};
};
这是请求:
let URL = "omitted";
request(getOptions(URL))
.then(response => {
// I do things with the response in here
}
})
.catch(function(err) {
console.log("Error %s", err);
});
我知道“ Access-Control-Allow-Origin”必须位于响应标头中,但我不确定如何实现。我是否需要在GET中发送某些标头,还是需要通过ServiceNow端完成此操作?我的GET请求通过Postman和普通的JavaScript文件工作,但不通过我的服务器工作。我已经为Chrome和Firefox安装了一个绕过CORS的插件,但我正在寻求实施适当的长期解决方案。
我在选项中尝试了这些标头,但我不太理解它们,因此它们无法正常工作。
headers: {
Origin: "my network address here",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "x-requested-with",
"Access-Control-Allow-Origin": "*",
Accept: "application/json",
"Content-Type": "application/json"
},
答案 0 :(得分:-2)
当尝试从未暴露给CORS的服务器访问API时,这是一个常见问题。
解决方案: 1.后备服务器需要明确接受CORS请求。 2.或者,您的后端代码和前端代码在同一服务器上运行。
出于开发目的,您可以通过使用以下命令在禁用安全性的情况下打开chrome浏览器来绕开CORS问题。
步骤:在系统中的某个位置创建目录,并更新命令中的路径,然后通过运行将其打开。
chrome.exe --user-data-dir =“” --disable-web-security