Axios-module: body parser on server middleware breaks POST request body on axios proxified requests

Created on 15 Jun 2018  路  8Comments  路  Source: nuxt-community/axios-module

Version

v5.1.0

Reproduction link

https://jsfiddle.net/8Ls7tafj/7/

Steps to reproduce

the steps to reproduce are in the fiddle, wich is just a nuxt.config.js exemple

What is expected ?

unaltered request body

What is actually happening?

request body is altered by body parser

Additional comments?

for people who experience the same issue, you can use this as a workaround
https://github.com/chimurai/http-proxy-middleware/issues/40#issuecomment-249430255

This bug report is available on Nuxt community (#c134)
bug-report

Most helpful comment

@mulhoon put following configuration in your nuxt.config.js

...
axios: {
    proxy: true
},
proxy: {
  '/api/': {
    target: process.env.URL,
    pathRewrite: { '^/api/': '/' },
    changeOrigin: true,
    onProxyReq: function log (proxyReq, req, res) {
      //  console.log(req.body)
      // console.log(proxyReq.getHeader('Content-Type'))

      if (!req.body || !Object.keys(req.body).length) {
        return
      }

      const contentType = proxyReq.getHeader('Content-Type')
      const writeBody = (bodyData) => {
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
        proxyReq.write(bodyData)
      }
      if (contentType.includes('application/json') || contentType.includes('application/x-www-form-urlencoded')) {
        writeBody(JSON.stringify(req.body))
      }
    }
  }
},
...

All 8 comments

Same issue here. After remove the body parser on server, now proxy request is working.

Unfortunately, there is nothing to do with this module.

But generally, it is much better to run API server separately from nuxt and instead, proxy /api to the API server which may be an express instance with body-parser. Combining SSR with API is often problematic.

It took a while to find the reason of timeouts that this is a problem of body-parser + proxy. I resolved this by adding a serverMiddleware after the bodyParser like this:

serverMiddleware: [
    bodyParser.json(),
    (req, res, next) => {
      req.removeAllListeners('data');
      req.removeAllListeners('end');
      process.nextTick(() => {
        if (req.body) {
          req.emit('data', JSON.stringify(req.body))
        }
        req.emit('end')
      })
      next()
    }
]

I fixed, using workaround from official github

https://github.com/chimurai/http-proxy-middleware/issues/320

I fixed, using workaround from official github

chimurai/http-proxy-middleware#320

Where did you put the code options.onProxyReq ... to get this working?
Do you have an example?

Many Thanks

@mulhoon put following configuration in your nuxt.config.js

...
axios: {
    proxy: true
},
proxy: {
  '/api/': {
    target: process.env.URL,
    pathRewrite: { '^/api/': '/' },
    changeOrigin: true,
    onProxyReq: function log (proxyReq, req, res) {
      //  console.log(req.body)
      // console.log(proxyReq.getHeader('Content-Type'))

      if (!req.body || !Object.keys(req.body).length) {
        return
      }

      const contentType = proxyReq.getHeader('Content-Type')
      const writeBody = (bodyData) => {
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
        proxyReq.write(bodyData)
      }
      if (contentType.includes('application/json') || contentType.includes('application/x-www-form-urlencoded')) {
        writeBody(JSON.stringify(req.body))
      }
    }
  }
},
...

Thank you @alexanderniebuhr 馃檹馃徎

@alexanderniebuhr 's code Solved my problem, in case others searching for this :

Vue ( Element Admin ) + webpack dev server + axios POST request with json body,

If you're confronted with error message like "Error occurred while trying to proxy request (ECONNRESET)", add above snippet into your vue.config.js proxy section.

Just paste my configuration for your information:

devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // change xxx-api/login => mock/login
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        target: `http://example.com:8084`,
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API + '/some-api']: ''
        },
        headers: {
          'Connection': 'keep-alive'
        },
        onProxyReq: function log(proxyReq, req, res) {
          //  console.log(req.body)
          // console.log(proxyReq.getHeader('Content-Type'))

          if (!req.body || !Object.keys(req.body).length) {
            return
          }

          const contentType = proxyReq.getHeader('Content-Type')
          const writeBody = (bodyData) => {
            proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
            proxyReq.write(bodyData)
          }
          if (contentType.includes('application/json') || contentType.includes('application/x-www-form-urlencoded')) {
            writeBody(JSON.stringify(req.body))
          }
        }
      },
    },
    before: require('./mock/mock-server.js')
  },
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ealves-pt picture ealves-pt  路  3Comments

lyzs90 picture lyzs90  路  4Comments

megapctr picture megapctr  路  5Comments

artmarydotir picture artmarydotir  路  4Comments

monty086 picture monty086  路  3Comments