Search code examples
jsonwebpackparametersaxiospayload

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


I have a webpack-dev-server config like

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));
      });
    }
  }
}

The equivalent axios call is like

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

I'm able to hit the route because I got the console.log(CircularJSON.stringify(req)) output, but the req.query & req.params are empty. I suspect it is due to the fact that I was sending JSON data, but even with extra axios config {headers: { 'Content-Type': 'application/json' }} I couldn't get the data I wanna send.

Any idea ?


Solution

  • the solution was to use '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));
          });
        }
      }
    }