我安装了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-Control-Allow-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.
有人知道这是怎么回事吗?
答案 0 :(得分:2)
这是一个错字。
在您的fetch
调用中,您将body
定义放在headers
对象中。这就是错误消息显示的原因:
请求标头字段 body 不允许...