简体   繁体   English

请求正文在 Post 中为空

[英]Request body is empty in Post

The following is a test file written with reference to my previous question: model.save() returns an invalid output .以下是参考我之前的问题编写的测试文件: model.save() 返回无效的 output

// Imports
var express=require("express")
, mongoose=require("mongoose")
, bodyParser= require('body-parser')
, bodyParser = require("body-parser");
const { Int32 } = require("bson");


// Constants
const app = express()
const PORT=4002

// Create a model
const dataModel=mongoose.model('dataCollection',mongoose.Schema(data))




// Our Schema
var data={
    value: Number
}

// Making connection with database
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/testdb', {
    useNewUrlParser:true,
    useUnifiedTopology:true
})


// Create the controller to save data
function postData(req,res){
    console.log(req.body)
    let newData = new dataModel(req.body)
    newData.save((err,resp)=>{
        if(err) console.log(err)
        else res.json(resp)
    })
}

// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));

// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);

// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

// start listening on server
app.listen(PORT,()=>console.log(`Your application is running on Port: ${PORT}`));



The above code prints undefined for console.log(req.body) in controller function postData for the POST request shown here:上面的代码为此处显示的 POST 请求的 controller function postData中的console.log(req.body)打印 undefined : 在此处输入图像描述

You can imagine the request is coming from the top and goes to the bottom.您可以想象请求来自顶部并到达底部。

It does not make sense to parse the body after you visited the route.在您访问路线后解析正文是没有意义的。 You need to parse the body first and THEN visit the route.您需要先解析正文,然后访问路线。

// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));

// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);

However bodyparsers isnt used anymore.但是 bodyparsers 不再使用。 You can use instead app.use(express.json())您可以改用app.use(express.json())

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

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