Login.js - react component.
I printed the JSON.stringify(credentials) object and it is valid but when i print the req.body in the server it is empty.
//sending a post request to the server with the username and password inserted by the user.
async function loginUser(credentials) {
console.log(JSON.stringify(credentials));
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(response => {
console.log(response);
})
};
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
you have to use a middleware to parse the json body in the post request,
you have not used bodyParser.json() as middleware
below is your updated code
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
Related
I try to do API call from my react app to my nodejs server.
Here is the server code.
const express = require('express')
const app = express()
const port = 80
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)
And the react app code
function callServerWebhook(data) {
fetch('http://<IP>/api', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: JSON.stringify({'username': 'foo', 'password':'bar'})
})
}
When i print the req.body, it's give me an empty object. What i'm doing wrong?
You need both bodyParser.json() and bodyParser.urlencoded() to correctly parse the data:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
I am trying to build a full stack(MERN) application. When I'm sending a request to my Express server with a JSON, I always see my req.body is empty. I can nowhere see my JSON inside my request.
I have tried using only app.use(bodyParser.json()) and app.use(bodyParser.urlencoded({ extended: true }));,but no change.
index.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
console.log("App");
require("./schema/data");
require("./routes/home_routes")(app);
require("./routes/table_routes")(app);
require("./routes/utility_routes")(app);
utility_routes.js
const mongoose = require("mongoose");
const Data = mongoose.model("data");
module.exports = app => {
app.get("/api/search_member", (req, res) => {
console.log("Utility", req);
console.log("Req Done");
// const search = await Data.findById({ member_id: req.body.member_id });
// console.log(search);
});
};
request.body
[0] body: {},
[0] route:
[0] Route {
[0] path: '/api/search_member',
[0] stack: [ [Layer] ],
[0] methods: { get: true } } }
request from client
onSearch = async value => {
console.log(value);
if (value) {
const searchData = await axios.get("/api/search_member", { value });
console.log(searchData);
}
};
You are making a GET request. GET request do not send body. To get req.body, make POST request to server.
Firstly:-
const searchData = await axios.post("/api/search_member", { value });
And Secondly,
app.POST("/api/search_member", async (req, res) => {
console.log("Utility", req);
console.log("Req Done");
});
This is what I use to accept the json
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json());
app.use(cookieParser());
And in the request set headers like this.
Content-Type : application/json
Both the axios and http libraries from angular works with this settings for me.
Unfortunately I get an empty body: {} in the request object, when I POST something to my api via Insomnia (configuration Form Form URL Encoded Header Content-Type: application/x-www-form-urlencoded):
Here is my express code:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.send("Hallo");
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
What am I doing wrong? And also what would I have to change in my code if I'd configure Insomnia to Form as JSON, Header Content-Type: application/json ?
For accessing request body use body-parser middleware and for sending the response in JSON format use res.json()
https://www.npmjs.com/package/body-parser
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.json({"message":"Hallo"}); //update here
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
available in Express v4.16.0 onwards:
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
Not able to get any data in the following post request , any suggestions ?
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlEncodedParser = bodyParser.urlencoded({extended:false});
var app = express();
// add Service
app.post('/api/service/addService',urlEncodedParser, (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});
Will you try this
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
after that write your code -
app.post('/api/service/addService', (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});
In node express when I try to access the post value from the form it shows request body undefined error.
Here is my code,
http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );
}).listen(9000, function() {
console.log('http://localhost:9000');
});
Please any one help me to find why the request body shows undefined.
Enable body-parser middleware first
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
If you're not using express for the web server and just plain http. Use the body module.