我正在尝试使用基本身份验证在fetch
上将ReactJS
用作API(这是一个复杂的请求)。
我偶然发现了许多文章,大多数都建议修改node
上的内容,但是在这种情况下,我没有使用任何节点服务器。我已注释掉所有NodeJS
代码,并且我是直接从componentDidMount()
获取此API,显然,ReactJS
有它自己的后端服务器。我暂时使用第三方cors chrome插件,但我不赞成使用第三方代理服务器,例如Heroku
或NGINX
或第三方库,例如axios
。 Cors chrome插件帮助我解决了access-control-allow-origin
问题,但随后引发了这个新问题。
Access to fetch at 'https://server-iam-fetching/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我尝试了一些操作,例如在标头上附加访问控制检查,但似乎没有任何作用。这是我的示例代码:
let headers = new Headers();
headers.append("Access-Control-Request-Headers", "*")
headers.append('Authorization','Basic ' + btoa(username + ":" + password));
credentials
allow requests
allow origins
..
..
etc
const someRequest = new Request(url, {
method: 'GET',
headers:headers,
mode:'cors',
cache: 'default'
});
componentDidMount(){
fetch(someRequest)
.then(response => response.json())
.then(json => console.log(json))
}
随时对任何问题发表评论。我在MacOS上。另外,我也不想禁用Chrome Web安全性。
此文章仅用于您的[[开发模式,您可以启动一个没有安全模块的Google Chrome实例,它不会发送OPTION
呼叫,并且绝对不会看到CORS错误,因此请打开您的终端并在其中写入以下命令:
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security