我在 React 中编写 axios post 方法并添加 Access-Control-Allow-Origin 但请求不起作用并响应我 cors origin 错误
Posted
技术标签:
【中文标题】我在 React 中编写 axios post 方法并添加 Access-Control-Allow-Origin 但请求不起作用并响应我 cors origin 错误【英文标题】:I write axios post method in React and add Access-Control-Allow-Origin but request is not working and response to me cors origin error 【发布时间】:2019-09-18 01:30:13 【问题描述】:我在 React 中编写 axios post 方法并添加 Access-Control-Allow-Origin 但请求不起作用并发送此响应:
从源“http://0.0.0.0:3000”对“https://api.aaaa.com/aaa/login/”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-origin .
axios.post('https://api.aaa.com/aaa/login/', userlogin ,
headers :
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://api.aaa.com',
'Access-Control-Allow-Credentials': true,
)
在后端代码 (Django) 中,我添加了 corsheaders 包和 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ['http://0.0.0.0:3000/']
我该如何解决这个错误?
【问题讨论】:
将 api.aaa.com 更改为 * 在api端添加标题为Access-Control-Allow-Origin: *
【参考方案1】:
CROS 必须从 webservice 添加,例如,如果 api(https://api.aaaa.com/aaa/login/) 是 用 php 编写,然后在 php 脚本中添加以下标题:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
对于 Django:
pip install django-cors-headers
然后将其添加到您安装的应用程序中:
INSTALLED_APPS = (
...
'corsheaders',
...
)
您还需要添加一个中间件类来监听响应:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:3030',
)
CORS_ORIGIN_REGEX_WHITELIST = (
'localhost:3030',
)
【讨论】:
以上是关于我在 React 中编写 axios post 方法并添加 Access-Control-Allow-Origin 但请求不起作用并响应我 cors origin 错误的主要内容,如果未能解决你的问题,请参考以下文章
使用 React、Redux 和 Axios 处理异步请求?
使用 axios 在 react-native 中使用 POST 方法获取 API 数据
react-hook-form axios post - 无法创建有效负载