我正在使用angular和nodejs,我从angular端数据正确注册新用户转到nodejs端,但是当我控制台req.body时,在nodejs端,它为我提供了带值的属性,但是当我想获取单个属性值时它给我错误未定义 这是我的index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
//this line is use to connect with mongodb
const {mongoose} = require('./db.js');
var userController = require('./controllers/userController.js');
const app = express();
app.use(bodyParser.json());
app.use(cors({ origin : 'http://localhost:4200' }));
// it,s listening port 3000
app.listen(3000,() => { console.log('app listen port : 3000'); });
//here is the user operation start
app.use('/user',userController); //end of the user operation
这是我的userController文件
router.post('/',(req,res) => {
var newUser = new User({
firstName:req.body.firstName,
firstLast:req.body.lastName,
emailAddress:req.body.emailAddress,
passowrd:req.body.password,
user_role:2,
account_status:1,
});
var recordExist = false;
User.findOne({emailAddress:req.body.emailAddress},(error,doc) => {
if(doc)
recordExist = true;
else
console.log('there is an error to get record with given email :' + req.body.emailAddress);
});
res.send(req.body.emailAddress);
});
当我控制台req.body时,它会给我所有带有值的ok属性 但是当我控制台req.body.emailAddress时,s给我未定义的
firstName: "abubakkar", lastName: "khan", emailAddress:
"abubakkar.tahir.khan@gmail.com", password: "12345"} firstName:
"abubakkar" lastName: "khan" emailAddress: "abubakkar.tahir.khan@gmail.com" password: "12345"
答案 0 :(得分:0)
您需要将req.body解析为JSON
req.body = JSON.parse(req.body)
console.log(req.body.emailAddress) // now it will work