首页 > 解决方案 > webpack-dev-server (devServer) 没有收到来自 axios 的 json 数据 (payload) | req.query & req.params 为空

问题描述

我有一个 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.query&req.params是空的。我怀疑这是因为我正在发送 JSON 数据,但即使有额外的 axios 配置{headers: { 'Content-Type': 'application/json' }},我也无法获得我想要发送的数据。

任何想法 ?

标签: jsonwebpackparametersaxiospayload

解决方案


解决方案是使用“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));
      });
    }
  }
}

推荐阅读