Dasun
Dasun

Reputation: 612

How to consume JSON in Express JS?

In very new to express js. I just wrote a simple program to send JSON request through postman and get the response.

Why I can't get any response? it always says could not get any response. I go through several tutorials and could not figure out what exact missing here?. Here is my code.

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

    app.use(express.json);
    app.post('/',  (req, res) => {
        console.log(req.body);
        res.send(req.body);
    });

    app.listen(3000, () =>{
        console.log("Listen in port 30000");
    });

Upvotes: 1

Views: 555

Answers (2)

Juhil Somaiya
Juhil Somaiya

Reputation: 943

You have to parse your json data inorder to consume it. check the following code.

install this package. npm i body-parser

and use it with your express object as below

let bodyParser = require('body-parser')

app.use(bodyParser.json())

Upvotes: 0

Dasun
Dasun

Reputation: 612

I figure out what went wrong. Here

app.use(express.json);

Should be This,

app.use(express.json()); 

Upvotes: 2

Related Questions