mazy
mazy

Reputation: 690

Express js - request body is empty

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?

Upvotes: 3

Views: 4998

Answers (5)

Thach Van
Thach Van

Reputation: 1539

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.

Upvotes: 1

Jamil
Jamil

Reputation: 939

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.

Upvotes: 0

Luca Marzi
Luca Marzi

Reputation: 806

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

Upvotes: 0

oliveromahony
oliveromahony

Reputation: 471

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

Upvotes: 1

nordhagen
nordhagen

Reputation: 809

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.

Upvotes: 6

Related Questions