Alexander Kleinhans Alexander Kleinhans - 7 months ago 24
Javascript Question

Get post data in NodeJS

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?
});

Answer

You can use the body-parser middleware on your Express route:

$ 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
})