I make a ajax call via code below and expect to see parameters passed nodejs app, but it always empty
#action postData() {
$.ajax({
url:"http://localhost:8080/sendMail",
ContentType:'application/json',
dataType:'json',
type:'post',
data:JSON.stringify({'message':'helloworld'}),
success:(result) =>{
..
})
If I make a post request within postman(adding raw string json parameters to body; {'message':'helloworld'}) its passed well and I see its logged. So whats wrong with this ajax call that i used in reactjsapp ?
Edited: it looks all parameters passed in browser fine but somehow nodejs unable to get them..
Since POST data is sent in the HTTP body, you need to parse the JSON in there to get it. Assumed you use express.js on the server side, you could use body-parser to do that:
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())
Related
I have an API that works as expected from all incoming requests using application/json request. But recently I encounter the need to process a POST request from x-www-form-urlencoded and the body of the request is always empty.
I test the API using POSTMAN and works great when I send the request using the option raw with JSON(application/json). But when send data using x-www-form-urlencoded the body is empty.
The route for the POST is app/api/sensor, and the files are the following:
app.js
var express = require('express');
var app = express();
.......
app.use(express.json());
app.use(express.urlencoded()); // THIS SHOULD WORK!
......
sensor.js POST
......
sensorRoute.post('/', (req, res, next) => {
console.log(req.body);
const temperature = req.body.temperature;
console.log(temperature);
if (!temperature) {
return res.status(400).send({'res': 'Missing data'});
} else {
return res.status(200).send({'res': 'OK'});
}
});
....
The expected result should show the data that is been send using postman in the req.body and not an empty object, and work the same as the application/jason.
change
app.use(express.urlencoded());
to
app.use(bodyParser.urlencoded({
extended: true
}));
The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.
Defaults to true, but using the default has been deprecated. so add the option extended: true
I'm trying to take a json collection of data and send it with postman or Advanced REST Client. The biggest thing I'm getting stuck with with is where the data is. I can't seem to find it in any part of the request. Note this must be done using express.
app.put('/api/', function (req, res) {
//Get data and replace table in database
res.send("RECEIVED");
});
You can use body-parser to parse the request and provide you all that submited data through request.body.data if you send you data as a form-data or request.params.data if you send your data as a query parameter.
npm install body-parser --save
And import it and use it as a middleware
var bodyParser = require("body-parser");
// some other code goes here like
// var express = require("express"):
// var app = express()
// and here attach the body-parser middleware like thiss
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
when you make a request with any Advanced REST client each key in the JSON that you pass to the request body will be accessible as request.body.key you can learn more about body-parser body-parser doc
I'm receiving data on a webhook URL as a POST request. Note that the content type of this request is application/x-www-form-urlencoded.
It's a server-to-server request. And On my Node server, I simply tried to read the received data by using req.body.parameters but resulting values are "undefined"?
So how can I read the data request data? Do I need to parse the data? Do I need to install any npm module? Can you write a code snippet explaining the case?
If you are using Express.js as Node.js web application framework, then use ExpressJS body-parser.
The sample code will be like this.
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
// With body-parser configured, now create our route. We can grab POST
// parameters using req.body.variable_name
// POST http://localhost:8080/api/books
// parameters sent with
app.post('/api/books', function(req, res) {
var book_id = req.body.id;
var bookName = req.body.token;
//Send the response back
res.send(book_id + ' ' + bookName);
});
You must tell express to handle urlencoded data, using an specific middleware.
const express = require('express');
const app = express();
app.use(express.urlencoded({
extended: true
}))
And on your route, you can get the params from the request body:
const myFunc = (req,res) => {
res.json(req.body);
}
The accepted answer uses express and the body-parser middleware for express. But if you just want to parse the payload of an application/x-www-form-urlencoded ContentType sent to your Node http server, then you could accomplish this without the extra bloat of Express.
The key thing you mentioned is the http method is POST. Consequently, with application/x-www-form-urlencoded, the params will not be encoded in the query string. Rather, the payload will be sent in the request body, using the same format as the query string:
param=value¶m2=value2
In order to get the payload in the request body, we can use StringDecoder, which decodes buffer objects into strings in a manner that preserves the encoded multi-byte UTF8 characters. So we can use the on method to bind the 'data' and 'end' event to the request object, adding the characters in our buffer:
const StringDecoder = require('string_decoder').StringDecoder;
const http = require('http');
const httpServer = http.createServer((req, res) => {
const decoder = new StringDecoder('utf-8');
let buffer = '';
req.on('data', (chunk) => {
buffer += decoder.write(chunk);
});
req.on('end', () => {
buffer += decoder.end();
res.writeHead(200, 'OK', { 'Content-Type': 'text/plain'});
res.write('the response:\n\n');
res.write(buffer + '\n\n');
res.end('End of message to browser');
});
};
httpServer.listen(3000, () => console.log('Listening on port 3000') );
Express 4.16+ has implemented their own version of body-parser so you do not need to add the dependency to your project.
app.use(express.urlencoded()); //Parse URL-encoded bodies
Non-deprecated alternative to body-parser in Express.js
If you are creating a NodeJS server without a framework like Express or Restify, then you can use the NodeJS native querystring parser. The content type application/www-form-urlencoded format is the same as the querystring format, so we can reuse that built-in functionality.
Also, if you're not using a framework then you'll need to actually remember to read your body. The request will have the method, URL, and headers but not the body until you tell it to read that data. You can read up about that here: https://nodejs.org/dist/latest/docs/api/http.html
If you are using restify, it would be similar:
var server = restify.createServer()
server.listen(port, () => console.log(`${server.name} listening ${server.url}`))
server.use(restify.plugins.bodyParser()) // can parse Content-type: 'application/x-www-form-urlencoded'
server.post('/your_url', your_handler_func)
I want to log all the query parameters which are passed to my endpoint. whenever they call me ie through GET , POST. i am able to print all the GET query params but struggling with POST params.
i used req.body but that doesnt work it just prints [Object object] even JSON.stringify didnt help.
Can any one point me to right source to look for it
So POST parameters arrive in the HTTP request body, and this is handled as a stream of data chunks by node.js. So the first thing you must do is make sure you assemble the stream of chunks into a complete piece of data. Then you may want to parse it as either url encoded or JSON if that's what it is. The standard middleware for this is body-parser. You set it up like they say in the README:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!
next()
})
Express (or Connect's) bodyParser middleware is marked deprecated and users are advised to use instead:
app.use(connect.urlencoded())
app.use(connect.json())
However, when I run the an example from Node.js in Action, I use curl to fill out the form as suggested by the book:
curl -F entry[title]='Ho ho ho' -F entry[body]='santa loves you' http://abc:123#127.0.0.1:3000/api/entry
It doesn't work. req.body is not defined. Am I missing something? It works fine with bodyParser.
EDIT: SOLUTION as of Express 4
Parse json this way:
var bodyParser = require('body-parser');
...
app.use(bodyParser.json());
Parse urlencoded body this way:
app.use(bodyParser.urlencoded({extended: true}));
Then there is no deprecation warning. The extended: true (default) uses the qs module and false uses the querystring module to parse the body.
Don't use app.use(bodyParser()), that usage is now deprecated.
bodyParser is in fact the composition of three middlewares (see documentation and relevant source code): json, urlencoded and multipart:
json parses application/json request bodies
urlencoded parses x-ww-form-urlencoded request bodies
and multipart parses multipart/form-data request bodies, which is what you're interested in.
If you only specify json and urlencoded middlewares, the form data won't be parsed by any middleware, thus req.body won't be defined. You then need to add a middleware that is able to parse form data such as formidable, busboy or multiparty (as stated in connect's documentation).
Here is an example, using multiparty:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use('/url/that/accepts/form-data', multipartMiddleware);
app.post('/url/that/accepts/form-data', function(req, resp) {
console.log(req.body, req.files);
});
Don't forget that by using such middlewares you allow anyone to upload files to your server: it then your responsibility to handle (and delete) those files.