POST with Nodejs express - node.js

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

Related

req.body is empty in post api (only in my laptop)

I have created this post API, when I am trying to call it from postman req.body is null always, but the same API is working fine on my friend's laptop.
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true}));
const sayHi = (req, res) => {
res.send("Hi!");
};
app.get("/", sayHi);
app.post("/add", (req, res) => {
const { a, b } = req.body;
console.log(req.body)
res.send(`The sum is: ${a + b}`);
});
app.listen(5000, () => {
console.log(`Server is running on port 5000.`);
});
this is my postman request: https://i.stack.imgur.com/d6QAZ.png
update:- I tried the same on my other laptop and it is working fine. I don't know why this is not working in my work laptop.
Hey Once try this middleware and send a proper request from POSTMAN I think this will resolve your all issues..
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true}));

NodeJs: How to parse post request body

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

Get empty req.body when deployed on Heroku

I have a react app front end posting data to my server(use express) deployed on Heroku. Code works well when both client and server running on localhost, but when it's on Heroku, the req.body always gets empty object {}.
Can anyone point out what's going wrong here? Thanks in advance :)
React code:
axios.post("/api", data, {headers: { "Content-Type": "application/json;charset=utf-8" }})
Express code:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cors({origin: URL,credentials: true}));
app.post("/api", (req, res) => {const data = req.body; console.log(data);};
This run perfectly on my computer. The log and the response works just fine. Hope it helps. I think the problem could be you are sending a GET request instead of a POST request.
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({origin: new URL('http://localhost:3000'), credentials: true})) // Add this 'new' keyword to URL
app.post("/api", (req, res) => {
const data = req.body
console.log(data)
res.send(data) // Added this to allow request to end
})
// Added this part to start the server listen.
const port = process.env.PORT || 3000
app.listen(port , () => {
console.log('Server is 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;
});

Strange Response from express server

I created a simple server using expressjs and have post method but I got strange response to post article and I don't know why it happened. Could anyone mind helping me?
my expected is a JSON format.
Here is my app.js file
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
My postman. I log request body out but it is not as my expectation.
if you are sending form data(application/x-www-form-urlencoded) the you can do
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
You're sending the wrong request body via postman, your body should be JSON format, not form data
Try removing body-parser and use middlewares directly from express and set urlencoded to false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
See here urlencoded option documentation

Resources