bodyParser doesn't seems to work

大城市里の小女人 提交于 2019-12-02 10:04:57

问题


Sorry if this question may sounds "simple", but I can't get body-parser to work on this very simple example :

"use strict";

const PORT = 3000;
const express = require("express");
const bodyParser = require("body-parser");
const app = express();

app.post("/api/login", (req, res) => {
  if (!req.body) return res.sendStatus(400);
  res.send("welcome, " + req.body.username);
});


app.use(express.json());
app.use(bodyParser.json());

console.log(`Listen on port ${PORT}`);
app.listen(PORT);

Command line to try it :

curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/api/login

And it always respond with 400 ! I tried a lot of configuration and didn't find a solution.

I'm sure it's pretty simple because no one seems to have the same error, so I'm missing something but don't know what !

express : 4.16.2

body-parser : 1.18.2

Thanks for your help !

EDIT : The solution was that I needed to put the middleware before the route definition. I my case, body-parser isn't needed I could just use express.jon() built in API.

"use strict";

const PORT = 3000;
const express = require("express");
const app = express();

app.use(express.json());

app.post("/api/login", (req, res) => {
  if (!req.body) return res.sendStatus(400);
  res.send("welcome, " + req.body.username);
});

console.log(`Listen on port ${PORT}`);
app.listen(PORT);

回答1:


You're installing bodyparser as middleware after the route definition. Generally you want to define pre-route middlewares before the routes or separate routes out to different files.

Simply re-arrange your code as follows:

'use strict'

const PORT = 3000
const express = require('express')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json()) // note: this is before the route

app.post('/api/login', (req, res) => {
  console.log(req.body)
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

app.use(express.json())

console.log(`Listen on port ${PORT}`)
app.listen(PORT)

If you wish to use bodyparser in a separate file as a middleware, the common use is as follows:

routes/someroute.js

const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()

module.exports = (app) => {

  app.post('/a/route', jsonParser, (req,res) => {
      ...
  })

}


来源:https://stackoverflow.com/questions/48132355/bodyparser-doesnt-seems-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!