#Every dev must know this

3 messages · Page 1 of 1 (latest)

vital vault
#

Related article: https://stackoverflow.com/questions/59570754/err-http-headers-sentcannot-set-headers-after-they-are-sent-to-the-client-whi

I'm having a very trippy error, this is about the library http-proxy, it's proxy the request to the target url
I'll send the code below, and explain the error here:

scroll to the bottom you'll see the console.log, basically, GET route works, and POST doesnt, even when they are the same

Here's how it is used

app.get('*', (req, res) => {
    return getRequestProxied(targetUrl, cookieName)(req, res, () => {});
}
the same for post, app.post().

The GET function

function getRequestProxied(targetUrl, cookieName) {
    const proxy = httpProxy.createProxyServer({
        target: targetUrl,
        changeOrigin: true,
        selfHandleResponse: true,
        agent: new HttpsProxyAgent(`corporateProxyUrl`)
    });

    proxy.on('proxyReq', (proxyReq, req, res) => {
        console.log("GET 1-fixRequestBody");
        fixRequestBody(proxyReq, req);
        console.log("GET 2-fixRequestBody");
    });

    proxy.on('proxyRes', function (proxyRes, req, res) {
        //... code to retrieve and modify the response then send to client with res.send(response)
    });

    return (req, res) => {
        req = headerModifier(req, targetUrl, cookieName); // modify the headers of req
        proxy.get(targetUrl).web(req, res);
    };
}
#

The POST function

function postRequestProxied(targetUrl, cookieName) {
    const proxy = httpProxy.createProxyServer({
        target: targetUrl,
        changeOrigin: true,
        selfHandleResponse: true,
        agent: new HttpsProxyAgent(`corporateProxyUrl`)
    });

    proxy.on('proxyReq', (proxyReq, req, res) => {
        console.log("POST 1-fixRequestBody");
        fixRequestBody(proxyReq, req);
        console.log("POST 2-fixRequestBody");
    });

    return (req, res) => {
        req = headerModifier(req, targetUrl, cookieName); // modify the headers of req
        proxy.get(targetUrl).web(req, res);
    };
}

This is what prints in the console:

GET 1-fixRequestBody
GET 2-fixRequestBody
GET 1-fixRequestBody
GET 2-fixRequestBody
POST 1 -fixRequestBody
node:_http_outgoing:652
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
pure willow
#

Please use an appropriate title and picture