node拿不到post请求数据 req.body 一直返回的是一个空对象

本文讲述了作者在处理前端POST请求到后端并传递数据时遇到的问题,由于将请求体参数写错为data而非body,导致后端无法接收到数据。作者花费了一天时间排查,最终发现并修正了这个低级错误,提醒开发者注意代码细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

家人们,谁懂啊,我被我自己蠢哭了,竟然因为解决这个问题用了整整一天,下面是我解决这个问题的整个过程,记录一下。

 下面是我的代码,主要功能就是前端有个输入框,收集用户的数据,发起post请求,将数据发给后端,后端拿到数据之后,响应一个 ok:1 

// index.ejs
  <div>
        <div>用户名: <input type="text" id="username"></div>
        <div>密码: <input type="password" id="password"></div>
        <div>年龄: <input type="number" id="age"></div>
        <div><button id="register">注册</button></div>
    </div>

    <script>
        var username = document.querySelector("#username")
        var password = document.querySelector("#password")
        var age = document.querySelector("#age")
        var register = document.querySelector("#register")

        register.onclick = () => {
            console.log(username.value, password.value, age.value);
            fetch("/api/user/add", {
                method: "POST",
                data: JSON.stringify({
                    username: username.value,
                    password: password.value,
                    age: age.value
                }),
                headers: {
                    "Content-Type": "application/json"
                }
            }).then(res => res.json()).then(res => {
                console.log(res);
            })
        }
// user.js
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});

router.post('/user/add', function(req, res) {
    console.log(req.body);
    res.send({ "ok": 1 });
});

module.exports = router;

下面就出现问题了,前端发送请求,可以得到后端响应的 ok:1,但是后端却得不到前端发请求时传过来的数据,一直都是一个空对象。

然后我就去网上找解决方案,第一个解决方案:要加上以下代码

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

可是我发现我原本的代码里面就有这几句话,所以我断定不是这个问题。

于是我又找到了另一个解决办法,就是需要在 header 中将 Content-Type 设置成application/json,这样后台才可以获取到值,于是我发现我的代码里面也有这句话,所以我的代码没有毛病啊!!!,于是我就陷入了深深的怀疑中,为什么代码都写的好好的,就是不出效果呢。别人出现这个问题,通过这两种方法就可以解决了,为什么我的不行啊。

突然一位路过的学姐给了我灵感,她说是不是我数据就没有发过去,于是我回头看的时候,真的发现了这个罪魁祸首,那就是用 fetch 发请求传数据的字段是body,而不是data, 我人都傻了,竟然因为一个名字写错,浪费我一天的时间,呜呜呜。下面就是正确的代码

// index.js 
<div>
        <div>用户名: <input type="text" id="username"></div>
        <div>密码: <input type="password" id="password"></div>
        <div>年龄: <input type="number" id="age"></div>
        <div><button id="register">注册</button></div>
    </div>

    <script>
        var username = document.querySelector("#username")
        var password = document.querySelector("#password")
        var age = document.querySelector("#age")
        var register = document.querySelector("#register")

        register.onclick = () => {
            console.log(username.value, password.value, age.value);
            fetch("/api/user/add", {
                method: "POST",
                body: JSON.stringify({
                    username: username.value,
                    password: password.value,
                    age: age.value
                }),
                headers: {
                    "Content-Type": "application/json"
                }
            }).then(res => res.json()).then(res => {
                console.log(res);
            })
        }

所以,最后劝告大家,写代码的时候一定要细心,不要像我一样出现这种低级错误,不仅浪费时间,最主要还丢人啊!今天就说这么多吧,撤了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

M_emory_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值