reactjs - 如何从 React 发送 CORS 请求?
问题描述
我在使用标头中的令牌发送 CORS 请求时遇到问题。获取代码:
fetchApi() {
fetch('http://some-link.com',
{
headers: {
'Accept': 'application/json',
'auth-token': 'xxxxxxxxx'
},
method: "GET"
}).then(response => response.json())
.then(function(response){
this.setState({hits:response});
}).catch(function(error) { console.log(error); });
console.log(this.state.hits);
};
控制台日志:从源“ http://localhost:3000 ”获取“ http://some-link.com ”的访问已被 CORS 策略阻止:访问控制不允许请求标头字段 auth-token-预检响应中的允许标头。
网络请求日志:
General
Request URL: http://some-link.com
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: some_ip:80
Referrer Policy: no-referrer-when-downgrade
Response Headers
Access-Control-Allow-Headers: origin, x-requested-with, content-type, auth_token
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Length: 8
Content-Type: application/json
Date: Tue, 13 Nov 2018 13:30:35 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Debian)
Request Headers
Provisional headers are shown
Access-Control-Request-Headers: auth-token
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
有什么想法可能是错的吗?
解决方案
您必须更改服务器设置以允许标头“auth-token”。
完成此操作后,您的请求将生效。
您当前允许“auth_token”,而不是“auth-token”。
或者,在前端更改标题名称,如下所示:
headers: {
'Accept': 'application/json',
'auth_token': 'xxxxxxxxx'
}
推荐阅读
- javascript - 如何获取 JavaScript 中窗口打开的第二个窗口的引用?
- javascript - 如何将带有 json 对象的文件导入另一个 js 文件?
- flutter - Flutter:登录失败后不显示显示对话框
- angular - 如何滚动到Angular中的元素?
- python - 从 pandas 数据框中删除数字和用户的停用词
- .net - 如何用换行符替换字符串?
- go - 如何在 golang 中使用动态/任意字段创建结构/模型
- ssl - 如何将 TLSv1.2 和 TLSv1.1 添加到 ssl 协议?
- javascript - 多个 if else 条件的替代方法
- angular - NgModule 提供者不在 Angular 中提供服务