2

I believe the answer to this question is out of date because of this answer.

I've read solutions about a npm packaged called body-parser, but I don't want to use it if I can find another way. I just simply want to parse POST data in node.

I have an ajax function like this:

$.ajax {
    url: '/foo',
    method: 'POST',
    data: {foo: "foo", bar: "bar"}
}

something like:

app.post('/foo', function(req, res) {
    var postFoo = req.foo; // How do I do this? 
});
Alexander Kleinhans
  • 5,950
  • 10
  • 55
  • 111

2 Answers2

2

You can use the body-parser middleware:

$ npm install body-parser --save

Then:

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

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

app.post('/foo', function (req, res) {
  // req.body is a plain object
})
djfdev
  • 5,747
  • 3
  • 19
  • 38
0

Try

req.body.foo

like this:

app.post('/foo', function(req, res) {
    var postFoo = req.body.foo;
});

The request can hold a lot of information such as the requesting user, headers, and the body of the request. The body holds the actual data that was passed along by the ajax-request.

Simon
  • 871
  • 1
  • 11
  • 23