I'm working with an odata api, and when I'm using postman to do a GET request, works perfect and I get the response as I was expecting.
但是,当我从 React 应用程序使用 fetch 请求时,该请求会抛出 401,并使用与我之前在 Postman 中使用的相同的标头。它说Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
知道如何解决这个请求吗?
谢谢!
fetch('https://api4.successfactors.com/odata/v2/', {
method: 'GET',
headers: {
authorization: `Basic ${auth}`, //auth is the encoded base64 username:password
},
})
.then(response => response.json())
.then((response) => {
console.log('in response: ', response);
})
.catch((error) => {
console.log('in fetchJobs error: ', error);
});
This is the 401 that I'm getting....
这很可能是因为邮递员可能没有发送预检Options
在您之前请求GET
,并在收到GET
响应不执行任何类型的cors检查(因为无论如何它都没有真正意义)。
另一方面,当从网页运行代码时,Chrome 都会执行预检Options
为了确定允许发送到远程服务器的跨域请求参数并检查是否响应Options
req 有适当的Access-Control-Allow-Origin
标题上以授权您origin
(即您发出请求的页面的域)。
通常,飞行前Options
由浏览器发送到服务器,询问服务器是否允许执行即将执行的操作 - 在您的情况下,GET
。如果远程(跨域)服务器没有响应 prelightOptions
请求在响应中包含正确的标头,授权您GET
那么浏览器将不会发送。然而,你甚至还没有走那么远,因为对你的回应Options
请求本身甚至没有传递 corsorigin
check.
如果您控制服务器,则需要响应Options
通过设置请求Access-Control-Allow-Origin
响应的标头包含origin
您的请求页面,并设置Access-Control-Allow-Methods
包括GET
(并且可能OPTIONS
)。如果你不控制远程服务器,很可能任何普通的 api 服务(例如你试图访问的服务)在其后端都有一些配置,你可以在某处设置来授权你的服务器origin
.
您可以阅读有关 cors 行为的更多信息here
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)