我安装了django-cors-headers
,并在 settings.py 中设置了所有正确内容
CORS_ORIGIN_ALLOW_ALL = True
INSTALLED_APPS = [
'corsheaders',
...
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # new
...
以下是我提出帖子请求的方式:
fetch("http://localhost:8000/isaapi/isaitem/", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `JWT ${localStorage.getItem("token")}`,
body: "" //JSON.stringify(body)
}
})
.then(res => res.json())
.then(json => {
console.log(json);
})
.catch(error => console.error(error));
我检查了响应的标题:
Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with
Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 86400
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Wed, 09 Jan 2019 08:22:27 GMT
Server: WSGIServer/0.2 CPython/3.6.3
Vary: Origin
这表明我已经得到了"访问控制-允许-来源:*"。还尝试清除缓存,但仍然出现错误,如下所示
Access to fetch at 'http://localhost:8000/isaapi/isaitem/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field body is not allowed by Access-Control-Allow-Headers in preflight response.
有人知道这里出了什么问题吗?
这是一个
错字。
在fetch
调用中,将body
定义放在headers
对象中。这就是为什么错误消息说:
请求标头字段正文不允许...