Skip to content

Cannot proxy after parsing body #299

Closed
@connelhooley

Description

@connelhooley

I cannot re-send a proxied request's body after I have parsed it.

Using this recipe, this comment and this comment I have written the following example:

import express from 'express';
import proxy from 'http-proxy-middleware';
import bodyParser from 'body-parser'

const app = express();
app.use(bodyParser.json());
app.post('*', proxy({
    target: 'http://target.here.com',
    secure: false,
    onProxyReq: (proxyReq, req) => {
        if (req.body) {
            const bodyData = JSON.stringify(req.body);
            proxyReq.setHeader('Content-Type','application/json');
            proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
            proxyReq.write(bodyData);
        }
    }
}));
app.listen(2001, () => console.log('Listening'));

I get an error when trying to set the first header on the proxyReq saying: Cannot set headers after they are sent to the client.

If that is the case how does the recipe work?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions