Reputation: 29
I try to make to get post req.body value but I keep getting undefined when I console.log I am using ( "express": "^4.17.1", ) I tried without body-parser and with body-parser, I keep getting the same result I tried all solutions available in StackOverflow but I keep getting the same result as you can see in the server.js
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const _ = require("lodash");
const mongoose = require("mongoose");
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:true}));
//app.use(bodyParser.urlencoded({ extended: true }))
//var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(express.static("public"));
app.use(cors());
app.get("/", (req, res) =>
{
res.send("Hello");
});
app.post("/login", async (req, res) => {
// const username = req.body.username;
// const password = req.body.password;
const {username , password } = req.body;
console.log("username : " + username);
console.log(req.body);
res.json(username);
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 5000;
}
app.listen(port, function() {
console.log("Server has started Successfully at port " + port);
});
and this is the postman request
localhost:5000/login?username="salem"&password=1234567
and bellow the package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Salem",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"lodash": "^4.17.21",
"mongoose": "^5.13.2"
}
}
I hope this gives a clear idea about my issue
Best Regards Salem
Upvotes: 0
Views: 1504
Reputation: 307
You have to send the user details to the body from the postman or you can use the query object to retrieve the same from the URL.
see req.query
Upvotes: 0
Reputation: 2891
You are passing data as Query Parameters
localhost:5000/login?username="salem"&password=1234567
but fetching value from the req.body
const {username , password } = req.body;
What you should use is :
var username = req.query.username;
var password = req.query.password;
Upvotes: 4