NodeJs: How to parse post request body - node.js

I've been trying to use body-parser but it's deprecated so I'm doing this
var express = require('express')
var app = express()
app.use(express.static(__dirname))
app.use(
express.urlencoded({
extended: true
})
)
app.use(express.json())
app.post('/send-message', (req, res) => {
console.log('request', req.body);
res.sendStatus(200)
})
var server = app.listen(3000, () => {
console.log('server is listening on port', server.address().port)
})
And send post request from Postman
But in the console I get
server is listening on port 3000
request {}
Why request is empty? and how to catch it correctly?

select json from the dropdown menu where text is written, this will set the content-type header to application/json
text to json

Related

Request urlencoded body is empty in express

I'm trying to get url parameters in express 4.17.3 using the urlencoded middleware but the body is always empty, I reproducted it to a minimal code:
const express = require("express");
(()=>{
const app = express();
app.use(express.urlencoded());
app.get("/", async(req, res)=>{
console.log(req.body); //always print '{}'
res.send();
});
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
})();
Here's my request
http://localhost:83/?param1=42
What am I doing wrong?
A few things to break down. To answer your question to get params you can use
req.query so your code would be:
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
Addressing urlencoded it should be changed from:
app.use(express.urlencoded());
to:
app.use(express.urlencoded({ extended: true }))
good habit to not hard code the port so the line of code:
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
should be:
const PORT = process.env.PORT || 83
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
full working code example:
const express = require('express')
const app = express()
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 83
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
When using express I also like to implement nodemon and if you add this to your package.json:
"dev": "nodemon node index.js"
then in the terminal you can run:
npm run dev
you wont have to restart your server during development changes.

axios post request from frontend not recieving in node js backend

I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?
By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().
You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());

Not receiving post data on node.js

I have a very simple node.js server:
const express = require("express");
const app = express();
app.post("/searcharea", (req, res, next) => {
console.log("SEARCH AREA2");
console.log(req.body);
res.status(200).send({ok:true});
});
app.listen(3000, () => {
console.log("Server running on port 3000")
});
However when I use curl and send data to the server I get an undefined as the req.body. Here is my curl statement when testing.
curl --header "Content-Type: application/json"
--request POST
--data '{"username":"search":"here"}'
http://localhost:3000/searcharea
Any guidance would be appreciated.
I am not sure about this data structure : '{"username":"search":"here"}', but to ingest json data from an express server you are required to use the json middleware like this
const express = require("express");
const app = express();
//!Important
app.use(express.json());
app.post("/searcharea", (req, res, next) => {
console.log("SEARCH AREA2");
console.log(req.body);
res.status(200).send({ok:true});
});
app.listen(3000, () => {
console.log("Server running on port 3000")
});
By default, req.body will be undefined. You need to include some sort of middleware to parse the incoming body of the POST request. Express.js packages this with it in v4.x and above. The included one handles most POST bodies but does not handle multipart requests. You'll need something like multer for that Change your code to this:
const express = require("express");
const app = express();
// parse JSON request body
app.use(express.json());
app.post("/searcharea", (req, res, next) => {
console.log("SEARCH AREA2");
console.log(req.body);
res.status(200).send({ok:true});
});
app.listen(3000, () => {
console.log("Server running on port 3000")
});

How to parse req.body in node js

I am passing 10.0.0.12 value in axios get from react side to node , When I am trying to print req.body on node side it displays [object,object] how to get value from object?
This How I am sending req:
axios
.get("/ashjg/GetTfsItem",
{BuildNumber:event.target.value[event.target.value.length-1].BuildNumber},{headers: {'Content-Type':'application/json'}},
)
.then(response => {
console.log("responce data"+response.data);
if(response.status==200){
this.setState({TfsItemdata : response.data});
}else{
this.setState({errorMessage:"Data Not Available "})
}
})
.catch(error => {
this.setState({errorMessage:"Data Not Available for Crash Id "})
});
}
Node Js Side :
router.get("/GetTfsItem",function(req,res,next){
console.dir( "Inside GetTfsItem " + Jreq.body );
}
Try using body-parser like this:
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))
})
Remember you need to install body-parser:
npm i body-parser
In case if you are using express.js then you can do it like this:
const express = require('express')
const app = express()
const port = 3000
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.post('/handle',function(request,response){
var query1=request.body.var1;
var query2=request.body.var2;
});

POST with Nodejs express

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());

Resources