bodyParser doesn't seems to work

后端 未结 1 1853
天命终不由人
天命终不由人 2021-01-21 22:41

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;         


        
1条回答
  •  一整个雨季
    2021-01-21 23:12

    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) => {
          ...
      })
    
    }
    

    0 讨论(0)
提交回复
热议问题