Parse body from GET request using nodejs, express, body-parser?
Asked Answered
S

1

4

Is it possible to retrieve the body contents using express?

I started by trying body-parser but that doesn't seem to work with GET. Are there any modules which would work?

var express = require('express'),
  bodyParser = require('body-parser'),
  PORT = process.env.PORT || 4101,
  app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.route('/')
  .get(function(req, res) {
    respond(req, res, 'GET body contents:\n');
  })
  .post(function(req, res) {
    respond(req, res, 'POST body contents:\n');
  });

app.listen(PORT, function(err) {
  if (err) {
    console.log('err on startup ' + err);
    return;
  }
  console.log('Server listening on port ' + PORT);
});

/*
 * Send a response back to client
 */
function respond(req, res, msg){
  res.setHeader('Content-Type', 'text/plain');
  res.write(msg);
  res.end(JSON.stringify(req.body, null, 2));
}

This is response from GET:

GET body contents:
{}

And from POST:

POST body contents:
{
    "gggg": ""
}
Sideband answered 5/4, 2016 at 11:31 Comment(5)
Primo, GET request's does not have bodyArius
take a look at this: https://mcmap.net/q/40417/-http-get-with-request-bodyApothegm
GET request's does not have body. Use POST instead.Lawford
@bigdestroyer GET requests do allow a bodySideband
@Sideband While GETs can have a body, as per the HTTP spec, servers should ignore it, as it has no meaning. See this answer. What is the server going to do with all these UUIDs? It's probable that structuring the application differently is what's needed, an ultra-long URL is unlikely to be the right tool for the job...Dulcimer
A
7

GET requests don't have a body, they have query strings. In order to access a query string in expressJS you should use the req.query object.

res.end(JSON.stringify(req.query, null, 2));
Aeolotropic answered 5/4, 2016 at 11:33 Comment(6)
The problem is, I'd like user to submit a list of uuids in the GET request body. I will lookup these uuids against a db. There could be hundreds of uuids passed, should these all be put into query string?Sideband
@Sideband Why can't you use a POST request then? There is a limitation on the length of a query string, but it's fairly largeAeolotropic
I can use POST, but was trying to remain as RESTful as possible. I understand the limitation on length is large, but theres a possibility I could hit it.Sideband
It all depends on architecture and requirements. For example you can limit the number of items that can be processed in a batch, or you can make the whole process async, where you post the batch and then check the status of the batchAeolotropic
@Sideband If you want to remain RESTful, use GET headers. They achieve the same effect as POST (etc) body. Have a look at owasp.org/index.php/…Bruton
GET Statements can have Body. This was changed in 2014.Hau

© 2022 - 2024 — McMap. All rights reserved.