Reputation: 10675
I am making a POST request from Postman with JSON data having email and password but when I tried to show that in Postman's response window it's showing nothing.
It seems that the POST request is not sending the JSON data with a request or I might be something wrong while accessing the request data.
Here is my code:
const express = require("express");
const app = express();
const database = {
users: [
{
id: "1234",
name: "john",
email: "[email protected]",
password: "john",
entries: 0,
joined: new Date()
},
{
id: "123",
name: "sally",
email: "[email protected]",
password: "sally",
entries: 0,
joined: new Date()
}
]
};
app.get("/", (req, res) => {
res.send("This is working Get");
});
app.post("/signin", (req, res) => {
res.json(req.body);
});
app.listen(3000, () => {
console.log("Server Started at port number 3000");
});
Upvotes: 0
Views: 529
Reputation: 660
Step 1 :
If you are making request using raw(application/json)
then you need to install below npm that will parse you request data,
npm install body-parser --save
Plesae go throgh the below link for more info :
https://www.npmjs.com/package/body-parser
Step 2 : You need to add below line in your server file
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
Step 3 : Once you integrate the bodyParser
you can access your request data using req.body
Here is you code with solution :
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
const database = {
users: [{
id: "1234",
name: "john",
email: "[email protected]",
password: "john",
entries: 0,
joined: new Date()
},
{
id: "123",
name: "sally",
email: "[email protected]",
password: "sally",
entries: 0,
joined: new Date()
}
]
};
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
app.post("/signin", (req, res) => {
res.json(req.body);
});
app.listen(8080, () => {
console.log("Server has been started");
});
Upvotes: 2
Reputation: 429
Along with express, You need 'body-parser' module for post request to work,
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.raw());
const database = {
users: [
{
id: "1234",
name: "john",
email: "[email protected]",
password: "john",
entries: 0,
joined: new Date()
},
{
id: "123",
name: "sally",
email: "[email protected]",
password: "sally",
entries: 0,
joined: new Date()
}
]
};
app.get("/", (req, res) => {
res.send("This is working Get");
});
app.post("/signin", (req, res) => {
res.json(req.body);
});
app.listen(3000, () => {
console.log("Server Started at port number 3000");
});
Upvotes: 1