Express bodyParser 无法正常工作

xav*_*tic 4 json express body-parser

我有一个我无法弄清楚的 bodyparser 问题。

几周前,我使用 Express 创建了一个 REST API,并使用 bodyParser 从客户端读取 JSON 数据。一切正常,但今天早上我尝试启动我的应用程序,但我所有的 req.body.data 都未定义,实际上 body 等于 {}。

这是我的配置:

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Run Code Online (Sandbox Code Playgroud)

然后我配置我的路线。我已经看到您必须按此顺序声明,即在您的路线之前声明 bodyParser,这就是我所做的。原以为是版本问题,但升级几次后问题依旧。

我使用 HttpRequester 来模拟客户端。直到今天早上一切正常。

发送的数据示例:

{
  "username": "david",
  "password": "bowie",
  "email": "db@sfr.fr"
}
Run Code Online (Sandbox Code Playgroud)

然后有这个响应代码:

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());

app.use('/users', users);
Run Code Online (Sandbox Code Playgroud)

然后在用户中我只创建一个用户:

 // 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
 }
Run Code Online (Sandbox Code Playgroud)

在 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;
Run Code Online (Sandbox Code Playgroud)

}

我会做其他事情,例如检查用户名是否为空,但我认为粘贴它并不重要。

感谢您的回复,并为我的英语不好而感到抱歉...

小智 9

如果您使用 JSON 请求,则可以设置正确的 HTTP 标头。

内容类型:应用程序/json