问题
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