当我发布详细信息时,我正在尝试使用 node
和“body-parser”来设置基本 API:
localhost:3000/users?email=test.com&givenName=test
我的 req.body.email
为空,如何发布我的详细信息?我正在使用 body-parser
像这样:
// create express app
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())
我的 Controller :
exports.create = (req, res) => {
// Validate request
if (!req.body.email) {
return res.status(400).send({
message: "user cannot be empty"
});
}
// Create a user
const user = new user({
email: req.body.email || "No Emails",
givenName: req.body.givenName || "No Emails",
familyName: req.body.familyName || "No Emails"
});
// Save user in the database
user
.save()
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message ||
"Some error occurred while creating the user."
});
});
};
最佳答案
我尝试了与您类似的代码,并且工作正常,请确保您正在点击来自 Postman 的 POST 请求。请参阅下面的代码,
'use strict';
// Initialize an Express application
const express = require('express');
const app = express();
const port = 8080;
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// parse application/json
app.use(express.json());
app.use((req, res) => {
console.log(req.body);
res.json(res.body);
});
// Start the express application
app.listen(port, () => {
console.log(`server listening on port ${port}`);
});
关于node.js - API 帖子,空主体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101239/