POST API body 未定义的值?
POST API body values coming through undefined?
我正在使用猫鼬在 MEAN 堆栈上构建一个 API。 API 应该处理用户注册和身份验证。为了对此进行测试,我正在使用 chrome 扩展,postman 向 /signup
提交 post 请求。
app.use("/signup", bodyParser.urlencoded({ extended: false }));
app.post("/signup", Auth.userExist, function (req, res, next) {
if (!req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
console.log("email: " + req.body.email);
console.log("password: " + req.body.password);
} else {
//do create new user logic...
res.json({success: true, msg: 'Successful created new user.'});
}
});
在这里你可以看到我在 API 请求的 body 中发送的内容:
在控制台中,我得到这个:
TypeError: Cannot read property 'email' of undefined
为什么我的请求 body 没有通过?
尝试为您的端点配置正文解析器:
var bodyParser = require("body-parser");
app.use("/signup", bodyParser.urlencoded({ extended: false }));
在POSTMANselectx-www-form-urlencoded
中代替form
然后传递表单值。您的代码应该可以正常工作。
我正在使用猫鼬在 MEAN 堆栈上构建一个 API。 API 应该处理用户注册和身份验证。为了对此进行测试,我正在使用 chrome 扩展,postman 向 /signup
提交 post 请求。
app.use("/signup", bodyParser.urlencoded({ extended: false }));
app.post("/signup", Auth.userExist, function (req, res, next) {
if (!req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
console.log("email: " + req.body.email);
console.log("password: " + req.body.password);
} else {
//do create new user logic...
res.json({success: true, msg: 'Successful created new user.'});
}
});
在这里你可以看到我在 API 请求的 body 中发送的内容:
在控制台中,我得到这个:
TypeError: Cannot read property 'email' of undefined
为什么我的请求 body 没有通过?
尝试为您的端点配置正文解析器:
var bodyParser = require("body-parser");
app.use("/signup", bodyParser.urlencoded({ extended: false }));
在POSTMANselectx-www-form-urlencoded
中代替form
然后传递表单值。您的代码应该可以正常工作。