【发布时间】:2017-03-14 23:08:04
【问题描述】:
我无法弄清楚 bodyparser 的问题。
几周前,我使用 Express 创建了一个 REST API,并使用 bodyParser 从客户端读取 JSON 数据。一切正常,但今天早上我尝试启动我的应用程序,我的所有 req.body.data 都未定义,实际上 body 等于 {}。
这是我的配置:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
然后我配置我的路线。我已经看到您必须按此顺序声明,即 bodyParser 在您的路线之前,这就是我所做的。原以为是版本问题,但升级几次后问题依旧。
我使用 HttpRequester 来模拟客户端。直到今天早上一切正常。
发送的数据示例:
{
"username": "david",
"password": "bowie",
"email": "db@sfr.fr"
}
然后是响应代码:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use('/users', users);
然后在用户中我只是创建一个用户:
// Creation of a user.
router.post('/create', function(req, res) {
// We check current mistakes like username or password empty.
if (!userhelper.checkCreateUserRequest(req, res)) {
return;
}
// Save the user in BDD
}
在 checkCreateUserRequest 我这样做:
if (req.body.username == null || req.body.password == null || req.body.email == null) {
res.status(400).json({message: "malformed request", code: 1});
return false;
}
我会做其他事情,例如检查用户名是否为空,但我认为粘贴它并不重要。
感谢您的回复,抱歉我的英语不好......
【问题讨论】:
-
您能否添加一个代码 sn-p 以及您要发送的示例数据?
-
感谢您的回复,我已经更新了我的帖子
标签: json express body-parser