简体   繁体   English

Express 4.17.1 req.body 返回 undefined

[英]Express 4.17.1 req.body returns undefined

The code is split into 2 files: the main file: server.js the router file: user.js In the user.js file req.body returns undefined and doesn't save the data to database代码分为 2 个文件: 主文件:server.js 路由器文件:user.js 在 user.js 文件中 req.body 返回 undefined 并且不将数据保存到数据库

The data sent to /user/register returns 'Could not save to database'.发送到 /user/register 的数据返回“无法保存到数据库”。 I've tried bodyParser.json() and bodyParser.urlencoded({extended: true}), although it isn't required in express 4.17.x, and they do not work.我已经尝试过 bodyParser.json() 和 bodyParser.urlencoded({extended: true}),尽管 express 4.17.x 中不需要它,而且它们不起作用。 Other common solutions like app.use(express.json()) also didn't help.其他常见的解决方案,如 app.use(express.json()) 也没有帮助。

server.js服务器.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用户.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;

I would guess the initial request lacks the header Content-Type: application/json .我猜初始请求缺少 header Content-Type: application/json
So Express json parser ignores the request body as it is not typed as json.所以 Express json 解析器会忽略请求正文,因为它没有被键入为 json。
So the parser does not fill the req.body field.所以解析器不会填充 req.body 字段。

Try adding this header with this value ( Content-Type: application/json ) to your request.尝试将此 header 与此值( Content-Type: application/json )添加到您的请求中。

How you will do that depends on how you send this request ( curl, postman, javascript xhr, react/angular..., lib... )您将如何做到这一点取决于您如何发送此请求( curl、postman、javascript xhr、react/angular...、lib...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM