【Web前端问题】fetch请求设置Content-Type失败?

我看这篇文章https://segmentfault.com/a/11... 写的
代码如下

fetch(apiUrl, {

method: "POST",

body: JSON.stringify({ aaa: 1 }),

headers: {

'Content-Type': 'application/json',

},

});

后端php

  header("Access-Control-Allow-Origin:*");

header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

var_dump($_REQUEST);

结果

array(0) {

}

chrome开发工具查看request header

OPTIONS /LotteryAPP_MS/01Code/partner_react/api.php HTTP/1.1

Host: 127.0.0.1

Connection: keep-alive

Pragma: no-cache

Cache-Control: no-cache

Access-Control-Request-Method: POST

Origin: http://localhost:3000

User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

Access-Control-Request-Headers: content-type

Accept: */*

Referer: http://localhost:3000/

Accept-Encoding: gzip, deflate, br

Accept-Language: zh-CN,zh;q=0.8

没有看到Content-Type: application/json,也没有看到参数,请求变成OPTIONS而不是POST了?
我又试了一下,似乎和跨域有关?同域下的就不会这样?

加上mode:'no-cors',这样就变成可以post请求,从chrome开发者工具上看,也能看到参数和返回

fetch(apiUrl, {

method: "POST",

mode: 'no-cors',

body: JSON.stringify({ aaa: 1 }),

headers: {

'Content-Type': 'application/json',

},

}).then(function(response) {

response.text().then((r) => {

console.log(r);

}).catch((r) => {

console.log(r);

});

}, function(error) {

console.log(error);

});

但是,php还是获取不到,而且php的返回,这里用response.text()也拿不到

回答:

我自己找到了

options请求也称为预检请求(preflight request)。但不是所有的cors都会发生预检请求,与预检请求相对应的是简单请求(simple request)。如果是简单请求,那么请求应该符合以下条件:请求类型是GET/HEAD/POST之一请求头除了用户代理(浏览器)自带的(Connection, User-Agent)和Fetch spec as a “forbidden header name之外,用户只允许设置以下请求头:Accept
Accept-Language
Content-Language
Content-Type (but note the additional requirements below)
Last-Event-ID
DPR
Downlink
Save-Data
Viewport-Width
Width
Content-Type只能是以下类型:application/x-www-form-urlencoded
multipart/form-data
text/plain

如果不满足上面三点任何一点,那么请求都是非简单请求。对于这样的CORS请求会先发出一个预检请求,如果后端响应头(后端会返回一些字段,比如Access-Control-Allow-Method)允许这个非简单请求,那么将会发起我们实际创建的请求。经常可能会出现的一个问题是,我们在请求头设置了Content-Type: application/json,那么这个请求就变成了非简单请求。所以会首先发起预检请求。后端需要注意的问题是,对options请求和实际的请求最好分别处理。

作者:余皖林
链接:https://www.zhihu.com/questio...
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

回答:

应该是后端问题,你看看是不是不接受json类型的type,改用form的方式试试

回答:

fetch里面是直接这么传参数么?
这是我写的

以上是 【Web前端问题】fetch请求设置Content-Type失败? 的全部内容, 来源链接: utcz.com/a/138875.html

回到顶部