我正在Nodejs上工作,我正在使用expressjs,现在我正试图运行"adduser"Api (post方法Api),但我在console.log
中得到以下消息[object object]
这是我的路由文件代码
const express = require('express');
const apiController = require('../controllers/api.controller');
const router = express.Router();
router.post('/new', apiController.addUser);
A
这是我的控制器文件(api.controller.js)
const addUser = async (req, res) => {
const { firstName, lastName, age } = req.body;
console.log('post data is '+ req.body);
console.log('first name is '+ lastName);
console.log('age is '+ age);
if (!firstName || !firstName.trim() || !lastName || !lastName.trim() || age == null || age < 0)
return res.status(400).send({ statusCode: 400, statusMessage: 'Bad Request', message: null, data: null });
try {
const user = new User(firstName, lastName, age);
await user.save();
res.status(201).send({
statusCode: 201,
statusMessage: 'Created',
message: 'Successfully created a user.',
data: null,
});
} catch (err) {
res.status(500).send({
statusCode: 500,
statusMessage: 'Internal Server Error',
message: null,
data: null,
});
}
};
const addUser = async (req, res) => {
const { firstName, lastName, age } = req.body;
console.log('post data is '+ req.body);
console.log('first name is '+ lastName);
console.log('age is '+ age);
if (!firstName || !firstName.trim() || !lastName || !lastName.trim() ||
age == null || age < 0)
return res.status(400).send({ statusCode: 400, statusMessage: 'Bad
Request', message: null, data: null });
try {
const user = new schema({firstName, lastName, age});
await user.save();
res.status(201).send({
statusCode: 201,
statusMessage: 'Created',
message: 'Successfully created a user.',
data: null,
});
} catch (err) {
res.status(500).send({
statusCode: 500,
statusMessage: 'Internal Server Error',
message: null,
data: null,
});
}
};
使用const user = new schema({firstName, lastName, age});
req.body模式中的值检查请添加对象{}
确保app.js文件需要app.use(express.json());