Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

body parser on server middleware breaks POST request body on axios proxified requests #145

Closed
ggirodda opened this issue Jun 15, 2018 · 8 comments

Comments

@ggirodda
Copy link

ggirodda commented Jun 15, 2018

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
chimurai/http-proxy-middleware#40 (comment)

This bug report is available on Nuxt community (#c134)
@ghost ghost added the cmty:bug-report label Jun 15, 2018
@nmfzone
Copy link

nmfzone commented Dec 8, 2018

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

@pi0
Copy link
Member

pi0 commented Apr 5, 2019

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.

@pi0 pi0 closed this as completed Apr 5, 2019
@gbalcewicz
Copy link

gbalcewicz commented Sep 24, 2019

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()
    }
]

@alexanderniebuhr
Copy link

I fixed, using workaround from official github

chimurai/http-proxy-middleware#320

@mulhoon
Copy link

mulhoon commented Oct 10, 2019

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

@alexanderniebuhr
Copy link

alexanderniebuhr commented Oct 11, 2019

@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))
      }
    }
  }
},
...

@mulhoon
Copy link

mulhoon commented Oct 11, 2019

Thank you @alexanderniebuhr 🙏🏻

@Hao-Wu
Copy link

Hao-Wu commented Jan 17, 2020

@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')
  },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants