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);
Related
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?
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've tried the all solutions from some another stackoverflow posts but it didn't solved my issue.
Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var index = require('./routes/index');
var v1 = require('./routes/route');
app.use('/', index);
//routes for api
app.use('/v1',v1);
Here is my post controller
module.exports = {
createUser:function (req,res) {
console.log(req.body);
res.send('ok'+req.body.test);
}
}
req.body returns {} even if the request body contains the parameters.
I am checking the api's with postman plugin.
Update
Postman request
body-parser
The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body, or an empty object {} if there was no body to parse (or an error was returned).
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
A new body object containing the parsed data is populated on the request object after the middleware, req.body will contain the parsed data, this object will contain key-value pairs, where the value can be a string or array
The Content-Type is application/x-www-form-urlencoded
app.use(bodyParser.json()); // for json encoded bodies
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).
The Content-Type is application/json
application/json is used when you are posting the data {"test":"hello"} like this. www-form-url-encoded is used to get the data as key-value in object from the url when used the app.use(bodyParser.urlencoded({ extended: true }));. They both are different and have their own use cases
After removing the last 4 lines of code (to be sure you are configuring correctly the routes) and adding this test lines:
app.post('/ping', function (req,res) {
console.log(req.body);
res.send('ok ' + req.body.test);
});
let server = http.createServer(app);
server.listen(8899, function onstart() {
console.log('server listening');
});
When I run:
curl -X POST http://localhost:8899/ping -d '{"test": 1234}'
I get ok undefined, like you did. After adding the proper content-type header:
curl -X POST http://localhost:8899/ping -d '{"test": 1234}' -H "content-type: application/json"
it works like a charm and I get ok 1234. So I think you are missing the "content-type: application/json" header in your postman.
I've looked at various posts on this topic but am still running into an error with this.
Python code:
import requests
import json
url = 'http://127.0.0.1:8080/ay'
payload = {'some': 'data'}
r = requests.post(url, data=payload)
print r.text
print r.status_code
Node.js code:
var app = express();
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
app.post('/ay', function(req, res){
console.log(req.body);
res.send('done');
});
So I've looked at my req and even req.body but req.body returns undefined so I think it's with json=payload but I've also tried params=payload and data=json.dumps(payload)
Edit: I forgot to include bodyparser and urlencoded. I edited my code to show the changes.
You have to use body-parser to get JSON from request body
var bodyparser = require('body-parser');
app.use(bodyparser.json());
Client side, this is what I have happening:
function saveGrades() {
$.post("/savegrades", {classIndex: "classIndexId"}); }
Server side:
router.post('/savegrades', stormpath.loginRequired, function(req, res) {
console.log("Class index: " + req.body.classIndex);
console.log(req.body);
res.send(200);
});
My bodyParser settings are as follows:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
No matter what I have tried, req.body is empty and does not have the classIndex. What am I doing incorrectly? Why is the data not being posted to the server?
Edit: For the linked questions, I have gone through almost all relevant answers here and am unable to find a solution. It seems that that data is never being sent to the server whatsoever. The body is always empty when I check it with a debugger.
Can you please check the code,
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
implemented well before,
router.post('/savegrades',
Based on your comment,
Can you please trying adding Trying adding mime type (content type) in client.
Try this and send data through POSTMEN to verify that data is actually comming then send it through function
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/savegrades', function(req, res) {
console.log("Class index: " + req.body.classIndex);
console.log(req.body);
res.send(200);
});