3

I just installed the latest versions of modules. I can not get any GET or POST variables. What i do wrong? NODE: v0.12.2

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
    res.setHeader('Content-Type', 'text/plain')
    res.write('you posted:\n')
    res.end(JSON.stringify(req.body, null, 2))
});
app.listen(3000,function(){
    console.log("Started on PORT 3000");
})

http://localhost:3000/?token=devvvvv GET returns: you posted: {}

Thanks for answers, but problem with POST does not solved... POST token=as123ds on http://localhost:3000/ return empty array in req.body How can i solve this?

mazorati
  • 2,031
  • 3
  • 22
  • 22
mazy
  • 652
  • 1
  • 10
  • 18
  • you should use **only one login** instead of two and use that only login to edit your question... – Taifun Apr 20 '15 at 14:45

5 Answers5

6

You are submitting parameters via the query string and attempting to access them through the request body which in this case is empty.

The token parameter will be available in request.query like so:

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.query.token, null, 2))
});

If you only plan to submit parameters in the query string you should not need to mount the body-parser middleware at all.

nordhagen
  • 799
  • 5
  • 18
1

You should be using the req.query:

req.query

An object containing a property for each query string parameter in the route. If there is no query string, it is the empty object, {}.

api link

oliveromahony
  • 471
  • 4
  • 19
  • 2
    That would be the case if the route was set up like so: http://localhost:3000/:token and accessed like so: http://localhost:3000/devvvvv – nordhagen Apr 20 '15 at 12:57
1

You are parsing JSON from the request, so the POST from client must have 'Content-Type': 'application/json' in HTTP header. If not, you'll have empty request.body at server side.

Thach Van
  • 1,381
  • 16
  • 19
0

bodyparser module requires the http request's "Content-type" property equal to "application/json". It won't work for other values.

Luca Marzi
  • 786
  • 2
  • 8
  • 24
0

You have to check the request content type in the client, this link may help

Node (Express) request body empty

This is because bodyParser parses application/json, application/x-www-form-encoded and multipart/form-data, and it selects which parser to use based on the Content-Type.

Community
  • 1
  • 1
Jamil
  • 889
  • 8
  • 10
  • It may be a good idea to include the important details from that link in your answer, as links can go dead over time and the meaning of your answer may be lost entirely if/when that happens. – orangething Oct 07 '16 at 19:51