webpack-dev-server (devServer) 没有从 axios 接收 json 数据(负载)| req.query & req.params 为空

webpack-dev-server (devServer) doesn't receive json data (payload) from axios | req.query & req.params are empty

我有一个像

这样的 webpack-dev-server 配置
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references

module.exports = {
...
  devServer: {
    before(app) {
      app.all('/my/route', (req, res) => {
        console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
        
        // I wanna have access to sent payload from Axios here, eg:
        const result = {
          foo1: req.query.bar1,
          foo2: req.query.bar2
        }
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(result));
      });
    }
  }
}

等效的 axios 调用就像

axios.post('/my/route', {bar1: 'x', bar2: 'y'}).then(...) => {...})

我能够找到路线,因为我得到了 console.log(CircularJSON.stringify(req)) 输出,但是 req.queryreq.params 是空的。我怀疑这是因为我正在发送 JSON 数据,但即使有额外的 axios 配置 {headers: { 'Content-Type': 'application/json' }} 我也无法获得我想要发送的数据。

有什么想法吗?

解决方案是使用 'body-parser'

const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
const bodyParser = require('body-parser')

module.exports = {
...
  devServer: {
    before(app) {
      // use bodyParser for axios request
      app.use(bodyParser.urlencoded({ extended: true }))
      app.use(bodyParser.json())

      app.all('/my/route', (req, res) => {
        console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
        
        // access them on req.body:
        const result = {
          foo1: req.body.bar1,
          foo2: req.body.bar2
        }
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(result));
      });
    }
  }
}