Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

fetch 设置('Content-Type', 'application/json')报错

Fetch API cannot load http://172.16.37.174/index.php?r=api/UserLogin. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

clipboard.png

我想给后台传参数json串,设置headers,不管是new了一个header添加还是直接在headers里面添加都是报这个错误,后台是PHP的。有没有哪个大神清楚是怎么回事的。

解决办法:

(1)之前后台在设置跨域问题的时候没有加单引号,eg:add_header Access-Control-Allow-Origin *;
(2)没有加 add_header 'Content-Type' 'application/json;charset=utf-8';
现在代码设置如下:
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Content-Type' 'application/json;charset=utf-8';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; 

问题解决了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

注意一下 content-type 和 body 的类型对应, 应该就是类型不匹配导致的错误.
不同的 content-type 会要求你传不同类型的值
具体我也忘了, 你可以试一下
body: param
body: 'name=aaa&age=111'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...