在使用 Fetch做一个前端的post请求时,直接从网上抄了一段代码

export async function postData(url, data){
    const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors', // no-cors, *cors, same-origin
        headers: { 'Content-Type': 'application/json','Accept':'application/json' },
        body: JSON.stringify(data) // body data type must match "Content-Type" header
    });
}

 在本地测试时,一个有趣的事情发生了

从前端控制台我们可以得到一个415(这个一般是请求的文本格式有问题) 

 从后端看到的日志为

 Content type 'text/plain;charset=UTF-8' not supported

 实际上上述代码是添加了请求头了,同时从前端的请求信息中也可以得出

Content-Type: application/json

确实没有错,但是到了后端怎么回是text/plain呢?

各种操作都试了还是不行,最后发现因为设置了no-cors

问题是,当您在“模式”“no-cors”下工作时,标头变得不可变,您将无法更改其某些条目。您无法更改的头部之一是 Content-Type。当您将“mode”设置为“no-cors”时,您将只能更改这些标头:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type and whose value, once parsed, has a MIME type (ignoring parameters) that is application/x-www-form-urlencoded , multipart/form-data , or text/plain

In another words, in ‘mode’ ‘-no-‘cors’ you can only set application/x-www-form-urlencoded , multipart/form-data , or text/plain to the Content-Type 。

所以解决方案是停止使用 fetch 或将其更改为 ‘cors’ ‘mode’。当然,这只有在您的服务器也接受“cors”请求时才有效。

javascript - Fetch: post json 数据,application/json 变为 text/plain - SegmentFault 思否

 最后移除        mode: 'no-cors', // no-cors, *cors, same-origin 就可以了!!!

cors是和跨域问题有关的,解决跨域的问题还是很多方法的,除了添加头以外

Logo

鸿蒙生态一站式服务平台。

更多推荐