Skip to content

How can I print out request bodies #177

@garyns

Description

@garyns

Hi, I'm trying to create a small development proxy to print out to the console headers, query params, and body.

But I can't get the body and prioxy to work together, and all my research had not given me any obvious solution.

In the code below, when I enable bodyParsers, I get the body printed to the console, but any PUT or POST request that contains a body ends up hanging. With no bodyParsers, req.body is undefined (as pre express docs) and the proxied request completes successfully.

Any advise on how I might approach this?

Thanks in advance.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var proxy = require('http-proxy-middleware');

var apiProxy = proxy({
    target: 'http://localhost:7040',
    changeOrigin: true,
    onError: function(err, req, res) {
        console.error(err.message);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end(err.message);
    }
});

// When enabled I get body output, but server/proxy hangs and request never completes.
app.use(bodyParser.raw());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(function(req, res, next) {

    console.log('\n\nHeaders');
    console.log(req.headers);

    console.log('\nQuery');
    console.log(req.query);

    console.log('\nBody');
    console.log(req.body);

    next();
});

app.use(apiProxy);
app.listen(8888);

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