POSTing json to express using jQuery - json

I'm having an issue when sending JSON data from my client to a node server running express.
Here's a simple server that demonstrates my issue:
var express = require('express');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
app.use(express.logger());
});
app.listen(80);
app.post('/', function(req,res){
console.log(req.body);
console.log(req.body.number + 1);
});
This server simply logs all POST data to the console.
If I then paste the following into chrome's development console:
$.post('/', {number:1});
The server prints out:
{ number: '1' }
11
How can I stop the number I'm passing being interpreted as a string?
Is it something to do with the bodyParser middleware I'm using?
Any help appreciated!!

$.post sends url-encoded data, so what is really sent is number=1, which then is parsed as well as it can by bodyParser middleware.
To send json you have to use JSON.stringify({number:1}).
Using $.post unfortunately won't set the appropriate Content-Type header (express will handle it anyway), so it's better to use:
$.ajax({
url: '/',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({number:1})}
)

Related

How to get JSON Data sent through postman tool using post method?

I'm trying to get a JSON data which is sent as JSON data using postman tool and trying to receive it my post() method.
var express = require('express');
var app = express();
app.post('/myData',function(req,res){
console.log("--->",req.body);
});
var server = app.listen(8080,function(){});
This is the JSON data sent through postman tool
I'm getting undefined in my console as
"---> undefined"
I'm trying to retrieve the JSON data set in my postman tool to either my console or browser
Corrected. Please try to run this code.
var express = require('express');
var app = express();
app.post('/myData', function (req, res) {
req.on('data', function (data) {
console.log("--->",data.toString());
res.send("Received");
});
});
var server = app.listen(8080, function () { });
Add res.send(req.body); inside the app.post method.
app.post('/myData',function(req,res){
console.log("--->",req.body);
res.send(req.body);
});
Express usually uses a middleware called body-parser to parse the received JSON content. req.body will be empty if you don't enable body-parser or something similar. body-parser is built in for the latest versions of Express. It's enabled like this:
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
So the final code is like this:
var express = require('express');
var app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.post('/myData',function(req,res){
console.log("--->", req.body);
res.send('data received');
});
var server = app.listen(8080,function(){});
I've also added res.send('data received');, because you should send a response when you get a request on a valid endpoint.

No body in POST request

I'm working on a web-push notifications project. I want to send user subscriptions from my client to a node server.
Client side code
function sendSubscriptionToBackEnd(subscription) {
return fetch('/api/save-subscription/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
});
}
Server side code
app.post('/api/save-subscription/', function (req, res) {
console.log(req.body);
}
The subscription object is a standard subscription with "endpoint" and "keys". I have already tried printing the subscription on the client side before sending it and it appears to be valid.
The problem is that the "req" object on the server side doesn't contain any "body" key. So, I don't know how to grab the subscription on the server side.
You might need the body-parser middleware if you don't have it already.
That's what parses the body of http requests, and gives you a nice parsed object to deal with.
In your server side code:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json()); // <-- this guy!
app.post('/api/save-subscription', (req, res) => {
console.log(req.body);
return res.sendStatus(201);
});

How parse JSON properties from request body in express server?

I've set up a node server that passes requests to a utility class.
So far the POST request is hit but the mapping to the body property values are undefined. Bodyparser is also used in the post method to assist in the Json parse.
I stepped into the request and see that the body is populated and see that the property names are correct as shown in the paste below:
body: { '{\n\t"Email":"brian#gmail.com",\n\t"Dashboard_Name":"my dash 4",\n\t''},
But the below mapping to the values assinged via req.body.propertyname return undefined:
var p_email = req.body.Email;
var p_dashboardName = req.body.Dashboard_Name;
Question:
How can you parse JSON properties from request body in express server?
JSON object posted:
This is the JSON that I post to the server using Postman:
{
"Email":"brian#gmail.com",
"Dashboard_Name":"my dash 4"
}
Gist of the express server and associated utility method SaveUserProfile:
Express server -
var express = require('express');
var UserLDAP = require('./utilities/UserLDAP'); //utility file containing the POST method
var bodyParser = require('body-parser');
const url = require('url');
const app = express();
var sql = require('mssql');
const cors = require('cors');
const path = require('path');
sql.connect("********************************************************************")
.then((connection1) => {
sql.globalConnection = connection1;
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/OOO/SaveUserProfile', UserLDAP.SaveUserProfile)
app.listen(process.env.PORT || 4000 );
logger.info(`listening to port ${process.env.PORT}`);
}).catch((err) => {
res.status(500).send(err.message);
logger.error(err.message);
});
UserLDAP.js -
var sql = require('mssql');
var bodyParser = require('body-parser');
//Save User Profile
exports.SaveUserProfile = function(req, res) {
req.app.use(bodyParser.json());
req.app.use(bodyParser.urlencoded({ extended: true }));
var request = new sql.Request(sql.globalConnection);
console.log(req);
var p_email = req.body.Email;
var p_dashboardName = req.body.Dashboard_Name;
};
Turns out I had incorrect content-type set in Postman on the object being posted. Needed to be set as:
application/json; charset=UTF-8
Currently you have no way of knowing if a parser like body-parser.json has produced an error which seems the obvious place to start given the content is there but the result isn't.
I had a look at body-parser and found an issue that spoke to the problem of detecting a json error which I would expect to be good to know.
The developer suggested the following as one method.
app.use(errorFork(bodyParser.json(),
function (err, req, res, next) {
// do stuff with only body parser errors
}))
// this is an example; you can use any pattern you like.
function errorFork(middleware, errorHandler) {
middleware(req, res, function (err) {
if (err) {
return errorHandler(err, req, res, next)
}else{
return next()
}
})
}
It isn't a fix but it would give you more info. Something is going wrong with the parsing by what you have indicated the questin is what? The other thing I noticed about your pasted body content is that it isn't valid json (ignoring \n\t) you have a few rouge ' in there, worth checking. Try copying what is in body (raw) and put it through a json validator site like jsonlint.com just as a double check and see if body-parser is returning any errors.

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api

How do I consume the JSON POST data in an Express application

I'm sending the following JSON string to my server.
(
{
id = 1;
name = foo;
},
{
id = 2;
name = bar;
}
)
On the server I have this.
app.post('/', function(request, response) {
console.log("Got response: " + response.statusCode);
response.on('data', function(chunk) {
queryResponse+=chunk;
console.log('data');
});
response.on('end', function(){
console.log('end');
});
});
When I send the string, it shows that I got a 200 response, but those other two methods never run. Why is that?
I think you're conflating the use of the response object with that of the request.
The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.
If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.
Update for Express 4.16+
Starting with release 4.16.0, a new express.json() middleware is available.
var express = require('express');
var app = express();
app.use(express.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
Updated for Express 4.0 - 4.15
Body parser was split out into its own npm package after v4, requires a separate install npm install body-parser
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
For earlier versions of Express (< 4)
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
Test along the lines of:
$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}
For Express v4+
install body-parser from the npm.
$ npm install body-parser
https://www.npmjs.org/package/body-parser#installation
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res, next) {
console.log(req.body) // populated!
next()
})
For those getting an empty object in req.body
I had forgotten to set
headers: {"Content-Type": "application/json"}
in the request. Changing it solved the problem.
#Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).
In my case I needed to force content-type: text/plain to be parsed as json.
If you cannot change the content-type of the request, try using the following code:
app.use(express.json({type: '*/*'}));
Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:
app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
// echo json
res.json(req.body);
});
const express = require('express');
let app = express();
app.use(express.json());
This app.use(express.json) will now let you read the incoming post JSON object
Sometimes you don't need third party libraries to parse JSON from text.
Sometimes all you need it the following JS command, try it first:
const res_data = JSON.parse(body);
A beginner's mistake...i was using app.use(express.json()); in a local module instead of the main file (entry point).