我正在使用chrome 53.0.2785.116 m(64位)。
我在devtools上得到了以下标题。该问题标有“//”注释。内容类型真的不允许我们将它设置为application / json,我尝试了100种不同的方式。
import fetch from 'isomorphic-fetch';
const option = {
method: 'POST',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'aa':'bb'})
}
fetch('/books', opts)
.then(check401)
.then(check404)
.then(jsonParse)
.then(errorMessageParse);
请求标题
accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Content-Length:97
content-type:text/plain;charset=UTF-8 //What happen?
Host:127.0.0.1:8989
Origin:http://127.0.0.1:8989
Referer:http://127.0.0.1:8989/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
问题是当你在'模式''no-cors'工作时,Headers变成一个不可变的,你将无法改变它的一些条目。你不能改变的一个头是Content-Type。当您将'mode'设置为'no-cors'时,您将只能更改这些标题:
Accept
Accept-Language
Content-Language
Content-Type
并且,一旦解析,其值为MIME类型(忽略参数) application/x-www-form-urlencoded
, multipart/form-data
, 要么 text/plain
换句话说,在'mode'' - no-'cors'中你只能设置 application/x-www-form-urlencoded
, multipart/form-data
, 要么 text/plain
到了 Content-Type
。
所以解决方案是停止使用fetch或将其更改为'cors''模式'。当然,只有当您的服务器也接受'cors'请求时,这才有效。
以下是如何在Apache服务器中启用CORS的示例
SetEnvIfNoCase Access-Control-Request-Method "(GET|POST|PUT|DELETE|OPTIONS)" IsPreflight=1
SetEnvIfNoCase Origin ".*" AccessControlAllowOrigin=$0
SetEnvIfNoCase Origin "https://(url1.com|url2.com)$" AccessControlAllowOrigin=$0
Header always set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" env=IsPreflight
Header always set Access-Control-Allow-Headers "Content-Type, Authorization, Accept, Accept-Language" env=IsPreflight
Header always set Access-Control-Max-Age "7200" env=IsPreflight
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteCond %{ENV:IsPreflight} 1
RewriteRule ^(.*)$ $1 [R=204,L]
上面的代码将在必要时在响应中注入CORS头。
使用此代码,您的服务器将仅允许来自域“url1.com”或“url2.com”的CORS。
以下是一些参考资料
该 mode:"no-cors"
选项似乎是个问题。删除该选项和 Content-Type
应该设置为 "application/json"