我正在使用express框架在window中创建一个nodejs api。我经常使用body-parser.json()。但是req.body在linux中为空。该程序在Windows中可以正常运行,但是在linux中,req.body为空,req.body.name键未定义。
我已经尝试了以下步骤:- app.use(bodyParser.urlencoded({extended:true})) app.use(bodyParser.json())
const express = require('express'),
app = express(),
config = require('./config/configFile'),
route = require('./routes/userRoute'),
bodyParser = require('body-parser'),
mongoose = require('mongoose')
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json()) // with this you can send the data to api in json format
app.get('/',(req,res)=>{
res.send({
"message":"API started"
})
})
app.use('/api/',route)
mongoose.Promise = global.Promise
mongoose.connect(config.dbPath,{useNewUrlParser: true})
.then(()=>{
console.log("Db is connected")
}).catch(err=>{
console.log(err)
})
app.listen(config.serverPort,()=>{
console.log('server started')
})
const userModel = require('../models/userModel')
module.exports = {
"registerUser": (req,res)=>{
if(!req.body){
res.status(400).send({
"message": "User Detail Cannot be empty"
})
} else{
const user = new userModel({
name : req.body.name,
email : req.body.email,
password : req.body.password
})
user.save().then(data=>{
res.status(200).send(data)
}).catch(err=>{
res.status(500).send({
"message": err.message || "Something went wrong"
})
})
}
},
"login":(req,res)=>{
res.send({
"message":"This is an register method"
})
}
}
答案 0 :(得分:0)
在您的路由文件中,您可以处理POST请求,例如
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
// req.body will contain the body data.
res.send('respond with a resource');
});
module.exports = router;
答案 1 :(得分:0)
您需要在快速路由器上注册路由。 您的userRoute.js必须看起来像这样。
var express = require('express');
var router = express.Router();
router.post("/registerUser", (req,res)=>{
if(!req.body){
res.status(400).send({
"message": "User Detail Cannot be empty"
})
} else{
const user = new userModel({
name : req.body.name,
email : req.body.email,
password : req.body.password
})
user.save().then(data=>{
res.status(200).send(data)
}).catch(err=>{
res.status(500).send({
"message": err.message || "Something went wrong"
})
})
res.send(req.body)
}
});
router.post("/login", (req,res)=>{
res.send({
"message":"This is an register method"
})
});
module.exports = router;