On post request from POSTMAN req.body is sending the data but returns { } when submitting the form.
This is what I used as the middleware,
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
but the word bodyParser is marked with the message 'bodyparser is deprecated'.ts(6385),
The declaration was marked as deprecated here.
I tried using,
app.use(express.json());
app.use(express.urlencoded({ extended: false}));
but still its returning { } on req.body
See the coding line when you are registering dependencies, if you register express json, that should be before your route, so it's look like :
const express = require('express');
const app = express();
// middleware registered here
app.use(express.json());
// then your route
app.post('/someroute', async (req,res,next) => {
const { param1, param2 } = req.body;
try {
console.log(`${param1} and ${param2} written in terminal);
res.send('ok');
} catch (err) {
res.send('oopps');
}
})
Are you sure you're using correct headers when you're sending your POST request?
For .json() parsing, your headers should contain: Content-Type: application/json
For urlencoded() form data parsing, your headers should contain: Content-Type: application/x-www-form-urlencoded
Can you also share the CURL of your Postman request?
Related
I have problems receiving request in body format on my server.
I am using Express version 4.17.1. The documentation indicates that I don't have to use body-parserer, but I can do it directly with the express functionality "express.json ()"
However, I've been trying to get it to work for a long time but nothing happens: the console does not show anything. It seems that it does not recognize the request at all.
I'm doing all the request from Postman in body format JSON.
This is my code:
const express = require("express");
const formidable = require("express-formidable");
const cors = require("cors");
const dotenv = require("dotenv").config();
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(formidable());
app.use(cors());
(...)
app.post("/list", async (req, res) => {
try {
console.log(req.body);
} catch (error) {
return res.status(400).json({ message: error.message });
}
});
What am I doing wrong?
Thank you very much for your time and help in advance.
Express parse request body according to defined type in Content-Type header. Try to do request with header Content-Type: application/json.
I'm currently using express to handle a POST request, but when I POST using node-fetch, I send a body and then I console.log() the body received in express (server code). I get an empty object. Not sure why this is happening, I will include my code here below.
Server Code
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
// GET method route
app.get('/api/getHeartCount', function (req, res) {
res.send('GET request')
});
// POST method route
app.post('/api/sendHeart', function (req, res) {
res.sendStatus(200);
let fBody = JSON.stringify(req.body);
console.log("Got body: " + fBody); // When this is run, I get this in the console: Got body: {}
});
app.listen(3000);
POST request code
const fetch = require("node-fetch");
(async () => {
const body = { heartCount: 1 };
const response = await fetch('http://localhost:3000/api/sendHeart', {
method: "post",
body: JSON.stringify(body)
});
const res = await response.text();
console.log(res);
})();
you used the wrong bodyParser
You must use the bodyParser.json() middleware like so in order to be able to parse json and access the body at req.body
// this snippet will enable bodyParser application wide
app.use(bodyParser.json())
// you can also enable bodyParser for a set of routes if you don't need it globally like so
app.post('/..', bodyParser.json())
// or just for a set of routes
router.use(bodyParser.json()
bodyParser.json([options])
Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).
from : https://www.npmjs.com/package/body-parser#bodyparserjsonoptions
NOTE : don't forget to add the Content-Type: application/json to your requests if you are sending a json type body
UPDATE : as #ifaruki said, express is shipped with a built-in json bodyParser accessible via express.json() from : https://expressjs.com/en/api.html#express.json
You should parse the body of your request
app.use(express.json());
With the newest express version you dont need body-parser
I'm trying to get started with Twilio's Programmable Fax API and I have completed their getting started guide. However, when I receive the fax, I log the request body to the console. However, the body is just an empty object.
I'm not sure what is going wrong.
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// Parse any incoming POST parameters
app.use(bodyParser.json({ extended: false }));
// Define a handler for when the fax is initially sent
app.post('/fax/sent', (req, res) => {
// Let's manually build some TwiML. We can choose to receive the
// fax with <Receive>, or reject with <Reject>.
console.log(req.body);
const twiml = `
<Response>
<Receive action="/fax/received" mediaType="application/pdf" storeMedia="true"/>
</Response>
`;
// Send Fax twiml response
res.type('text/xml');
res.send(twiml);
});
// Define a handler for when the fax is finished sending to us - if successful,
// We will have a URL to the contents of the fax at this point
app.post('/fax/received', (req, res) => {
// log the URL of the PDF received in the fax
console.log(req.body);
// Respond with empty 200/OK to Twilio
res.status(200);
res.send(req.body);
});
// Start the web server
http.createServer(app).listen(3000, () => {
console.log('Express server listening on port 3000');
});
And here is what I get back in the console. You can see the empty object that is logged...
Express server listening on port 3000
{}
UPDATE:
I changed the body parser middleware to use urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
And I get the object but I don't see a media url...
With later versions of Express, 4.16.0 - Release date: 2017-09-28, you don't need to require body-parser.
// Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
BodyParser has updated since their documentation was written. You need to do
app.use(bodyParser.urlencoded({ extended: false }));
I have the below code. when I make a Post request via Postman I get req.body as undefined.
Post Request is http://localhost:1702/es.
Body:
{
"ip_a":"191.X.X.XX",
"pkts":34
}
and Content-Type:"application/json". I also used application/x-www-form-urlencoded but got the same result.
My app.js is:
var express = require('express');
var es=require('./routes/es');
var app = express();
app.post('/es',es.postesdata);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
And my file where I am receiving a request body null is:
exports.postesdata=function(req,res){
var body=req.body;
console.log(body);//Getting Undefined here
}
Am I doing something wrong here?
express runs middleware in order try:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/es',es.postesdata);
When using the following:
var app = require('express')();
var bodyParser = require('body-parser');
app.post('/test', bodyParser.json(), function(req, res) {
res.json(req.body);
});
var port = 4040;
app.listen(port, function() {
console.log('server up and running at port: %s', port);
});
and the following post from Postman:
I get an empty response. I've followed a lot of threads on using bodyParser.json() and for some reason I'm still receiving an empty object in response. What am I missing?
To make bodyParser.json works you should provide Content-Type header with value application/json in your requests.
A safer way to use body-parser would be to apply it as middleware for the entire app. The code will have to be refactored in this manner:
// Permit the app to parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// Use body-parser as middleware for the app.
app.use(bodyParser.json());
app.post('/test', function(req, res) {
res.json(req.body);
});
When you make a request on Postman, make sure to select the x-www-form-urlencoded tab as opposed to the raw tab.