简体   繁体   中英

request.body is not defined while sending json data from postman

Basically what i am trying to do is creating a customer collection in mongodb using expressjs . while i am sending the data from postman it is showing req.body is undefined .

my customer.js looks like this

const express = require('express');
const router = express.Router();
const fs = require('fs');

const Customers = require('../models/customer');


router.post('/addcustomer',(res,req,next)=>{
    const customer = new Customers({
        name:req.body.name,
        address:req.body.address,
        products:req.body.products,
    });

    customer.save()
    .then(result=>{
        console.log(result);
        res.json({message:"killer"});
    }).catch(error=>{
        console.log(error);
        res.json({error:error})
    });

and my app.js looks like this

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const morgan = require('morgan');


// route files include here
const UserRoutes = require('./api/routes/users');
const CustomerRoutes = require('./api/routes/customer');

// mongoose connection string
mongoose.connect('mongodb://127.0.0.1:27017/bdrs',{useNewUrlParser:true,useUnifiedTopology: true});

app.use(morgan('dev'));
app.use(express.json());
//Cors policies 
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin','*');
    res.header(
        'Access-Control-Allow-Header',
        'Origin,X-Requested-With,Content-Type,Accept,Authorization'
    );
    if(req.method == 'OPTIONS'){
        res.header(
            'Access-Control-Allow-Methods',
            'GET,POST,PATCH,DELETE,PUT'
        );
        return res.status(200).json({})
    }
    next();
});

//Routes for operations
app.use('/user',UserRoutes);
app.use('/customer',CustomerRoutes);



// error handling
app.use((res,req,next)=>{
    const error = new Error('Not Found');
    error.status = 404;
    next(error);
});

app.use((error,req,res,next)=>{
    res.status(error.status||500);
    res.json({
        error:{
            message:error.message
        }
    });
});

module.exports = app;

after that my postman request looks like this邮递员请求截图

邮递员的回应

i have done the similar code somewhere else and it is working fine. Dont know whats the issue here. Thanks in advance.

Your problem lies here

Change

router.post('/addcustomer',(res,req,next)=>{ 

To

router.post('/addcustomer',(req,res,next)=>{

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