fetch 配合 express 使用req body为空

  1. 前言

最近用 node 写后端接口 前端使用fetch,遇到个问题记录如下
使用fetch进行post请求的时候,后端node 使用express框架进行body接收的时候始终是个空对象 {}


2.后端代码

const express = require('express');
let app = express()

app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencod
//*************post 
app.post("/login",(req,res)=>{
    console.log("post------body",req.body)
    res.json({msg:"登录成功",code:1000})
})

3.前端代码

    <button onclick="loginFn()"> 登录 -post</button>

 let loginFn = async () => {
            let res = await fetch("/login", {
                method: "POST",
                body: JSON.stringify({ name: "1-1-1" }),

            }).then(res => res.json())
            console.log("post 结果:", res)
        }
2.png

4. 解决办法 配置请求头

headers 配置

let res = await fetch("/login", {
                method: "POST",
                body: JSON.stringify({ name: "yzs",password:"123456" }),
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                }
            }).then(res => res.json())
1.png

5.原因 找到了 MDN

fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
  .then(response => response.json())

body的数据类型 必须和 content-Type匹配
但是这个fetch默认的类型是text/plain ,这个需要的是纯文本

1.png


所以必须手动设置请求头

headers: {
              "Content-Type": "application/json; charset=utf-8"
            }

6.扩展

key-value形式对应的 content-type配置

 headers: {
    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
  },
    body: 'name=yzs&password=123456'

7. 后记

  1. 后端注意设置content-type,我这里是nodejs
     res.setHeader("Access-Control-Allow-Headers","X-request-With,content-type");


参考资料

fetch-MDN

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容