arslan
arslan

Reputation: 2234

Node.js how to read json data from request?

I have a server as following:

app.post('/', function(req, res, next) {
   console.log(req);
   res.json({ message: 'pppppppppppppssssssssssssss ' });   
});

The request is sent from a client as:

$.ajax({
    type: "POST",
    url: self.serverURI,
    data: JSON.stringify({ "a": "128", "b": "7" }),
    dataType: 'json',
    success: function (result) {
        console.log(result);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});

so far the connection fine.

My problem is in the server:

console.log(req);

where I want to read the data I sent. How can I read { "a": "128", "b": "7" } from req?

Upvotes: 9

Views: 22070

Answers (2)

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

For Express 4+,

const express = require("express");
const app = express();

app.use(express.json());

Then, you can use req.body as expected.

app.post("/api", (req, res) => {
  /*
    If the post request included { data: "foo" },
    then you would access `data` like so:
  */
  req.body.data
  ...
});

Upvotes: 5

qqilihq
qqilihq

Reputation: 11474

Although you're not mentioning it, your code looks like it's written for an Express environment. My answer is targeted to this.

Make sure to use body-parser for Express. In case, your project depends on some generated boilerplate code, it's most likely already included in your main server script. If not:

var bodyParser = require('body-parser');
app.use(bodyParser.json());

Installation with npm: npm install body-parser --save

The parsed JSON can then be accessed through req.body:

app.post('/', function(req, res, next) {
    console.log(req.body); // not a string, but your parsed JSON data
    console.log(req.body.a); // etc.
    // ...
});

Upvotes: 13

Related Questions