简体   繁体   中英

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

The data sent to /user/register returns 'Could not save to database'. 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. Other common solutions like app.use(express.json()) also didn't help.

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;

I would guess the initial request lacks the header Content-Type: application/json .
So Express json parser ignores the request body as it is not typed as json.
So the parser does not fill the req.body field.

Try adding this header with this value ( Content-Type: application/json ) to your request.

How you will do that depends on how you send this request ( curl, postman, javascript xhr, react/angular..., lib... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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