【问题标题】:Express 4.17.1 req.body returns undefinedExpress 4.17.1 req.body 返回 undefined
【发布时间】:2021-08-08 13:58:04
【问题描述】:

代码分为2个文件: 主文件:server.js 路由器文件:user.js 在 user.js 文件中 req.body 返回 undefined 并且不将数据保存到数据库中

发送到 /user/register 的数据返回“无法保存到数据库”。 我已经尝试过 bodyParser.json() 和 bodyParser.urlencoded({extended: true}),尽管 express 4.17.x 中不需要它,而且它们不起作用。 app.use(express.json()) 等其他常见解决方案也没有帮助。

server.js

const express = require('express')
const mongoose = require('mongoose')
const User = require("./models/userSchema");

const userRouter = require('./routes/user')
const placeRouter = require('./routes/place');
const bodyParser = require('body-parser');

const app = express()
const PORT = 5000

app.use(express.json())


mongoose.connect('mongodb://localhost:27017/instaDB', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, () => {
    console.log('Connected to Database');
})

app.use('/user', userRouter)



app.listen(PORT, ()=>{
    console.log(`Listening on PORT: ${PORT}`);
})

user.js

const express = require('express')
const User = require("../models/userSchema");

userRouter = express.Router()

userRouter.post('/register', (req, res) => {
    const {username, password} = req.body
    console.log(req.body.username);
    console.log(password);
    User.findOne({username}, (err, user) => {
        if(err){
            res.status(500).json({
                err: true,
                msgBody: 'Server Error'
            })
        } if(user){
            res.status(400).json({
                err: true,
                msgBody: 'Username already exists'
            })
        }
        else{
            const newUser = new User({
                username,
                password
            })

            newUser.save((err)=>{
                if(err){
                    res.status(500).json({
                        err: true,
                        msgBody: 'Could not save to database'
                    })
                } else {
                    res.status(200).json({
                        err: false,
                        msgBody: 'Registered Successfully'
                    })
                }
            })
        }
    })
})

   
module.exports = userRouter;

【问题讨论】:

  • 你是如何向你的服务器发出请求的?
  • 能否添加 curl 命令或将请求发送到服务器的代码行,它有助于解决问题?

标签: javascript node.js mongodb mongoose


【解决方案1】:

我猜初始请求缺少标头 Content-Type: application/json
所以 Express json 解析器会忽略请求正文,因为它没有键入为 json。
所以解析器不会填充 req.body 字段。

尝试将此标头与此值 (Content-Type: application/json) 添加到您的请求中。

您将如何做到这一点取决于您发送此请求的方式(curl、postman、javascript xhr、react/angular...、lib...

【讨论】:

  • 感谢您的帮助!我在邮递员请求中错过了那个标题
  • 嗨@KaranMishra,如果这个或任何答案已经解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 2020-08-27
  • 2017-08-30
  • 1970-01-01
  • 2021-05-05
  • 2019-05-17
  • 1970-01-01
  • 2016-06-28
相关资源
最近更新 更多