在获取请求中设置内容类型不起作用 [英] Setting Content-Type in fetch request not working

查看:37
本文介绍了在获取请求中设置内容类型不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向服务器发出远程获取请求。有效负载是JSON格式,所以我想将Content-Type头改为application/json。我使用了以下代码来完成此操作:

let email = document.getElementById("email").value
let password = document.getElementById("password").value

const body = {"email":email, "password":password}
const headers = new Headers({
    "Content-Type": "application/json",
    "Content-Length": JSON.stringify(body).length
})
const options = {
    method: "POST",
    mode: "no-cors",
    headers: headers,
    body: JSON.stringify(body)
}
console.log(options)
const response = await fetch('http://xx.xx.xx.xxx/login', options)
const json = await response.json()
console.log(json)

然而,在Chrome开发者工具控制台中,请求的Content-Type头仍然是text/plain;charset=UTF-8。我做错了什么?

推荐答案

no-cors请求不允许覆盖Content-Type请求标头。

将模式更改为cors

(如果不这样做,您也将无法阅读响应)。

这篇关于在获取请求中设置内容类型不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆