No body in POST request - json

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

Related

req.body is empty prototype in onRequest firebase cloud functions (With multer)

In my cloud function:
const app = express();
app.use(multer().array());
app.post("/", (req, res) => {
console.log("hit", req.body.from);
console.log("hit", req.body.from);
return res.sendStatus(200);
});
const emailInboundWebhook = functions.https.onRequest(app);
module.exports = {
emailInboundWebhook
}
I get this in logs:
i functions: Beginning execution of "emailInboundWebhook"
> hit undefined
> hit undefined
i functions: Finished "emailInboundWebhook" in ~1s
But when the same endpoint served as an express app(outside cloud functions):
const express = require("express");
const app = express();
const multer = require('multer');
app.get("/", async (req, res) => {
res.status(200).json({foo: "Bar"});
})
app.use(multer().array());
app.post("/webhook", async (req, res) => {
console.log("hit",req.body.to);
console.log("hit",req.body.from);
res.sendStatus(200);
});
app.listen(80, () => {
console.log("App listening on 80");
})
Gives this:
hit a#some-email-inbound.some.url
hit Rahul Priyadarsi <myemailid#gmail.com>
The two results are for same email sent and these functions are fired as sendgrid webhooks which send multipart/form-data POST requests that contain details of the email sent to a#some-email-inbound.some.url from myemailid#gmail.com
I have no idea as to why the two results are different(I am testing them via ngrok and since the console log lines run, clearly the function is hit).
I had the same problem.
Take a look in this issue: https://github.com/expressjs/multer/issues/572
Switch from Multer to Busboy, is also a good option.
One thing: In this situation use https.Request (from cloud-functions) instead of Request from express.

Node.js + body-parser object format changes when it reaches backend

I'm trying to send an object inside an another object from React frontend to Node/express backend using jquery ajax. The problem the data is received at the backend, it no longer looks follows the syntax of an object. Instead, it looks something like this:
{ 'data[name]': 'test name',
'data[size][height]': '123',
'data[size][weight]': '50' }
Here is the front end ajax call...
lendItem(){
let id = "5af3348742afc60ab71d7d80"
$.ajax({
url: '/api/items/' + id,
method: 'put',
data: {
'data': {
name: "test name",
size: {
height: 123,
weight: 50
}
}
},
success: (res) => {console.log(res)}
});
}
backend server...
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// connect to mongodb
mongoose.connect('mongodb://localhost/promedical');
mongoose.Promise = global.Promise;
const app = express();
const port = process.env.PORT || 5000;
// parsing data that was received
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// initialize routes
app.use('/api', require('./routes/api'));
// error handling
app.use((err, req, res, next)=>{
res.status(422).send({error: err.message});
});
app.listen(port, () => {
console.log(`Listening on port ${port}`)
});
...and here is the route I'm interested in.
router.put('/items/:id', (req, res, next)=>{
console.log(req.body);
res.send("success");
});
I think this problem might have something to do with that body-parser. Is is possible to send objects inside an object via jquery ajax and have it keep it's form once it reaches the backend? If not, should I just send all the data inside one object and then parse it at the backend?
It turns out that the object called 'data' becomes a string after the backend has accepted the ajax call. Is there any way to prevent this from happening? I need to store that object into a database as an object, not as a string.

HTML is being sent instead of JSON Data

I'm trying to retrieve data from a SQL database and display that said data on a Reactjs web app. However, all the calls I make to the database results in the HTML of the webpage in focus. I have set the headers, and I've tried to change the way the response from the express call is being handled.
Here is the expressjs script I am using right now:
const express = require('express');
const sql = require('mssql/msnodesqlv8');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const db = require('./db.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
app.use(cors());
app.get('/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
From there, my axios calls look like this:
componentWillMount(){
let self = this;
axios.get("/getTable")
.then(function (response){
console.log(response.data);
self.setState({
data: response.data,
});
})
.catch(function (error){
console.log(error);
})
}
I added the console.log to check what was being returned, and as said, it was the HTML code of the current page of focus.
I made some changes to reflect what steps I took to get the 500 issue out. The current code, however, results in a 404.
If you move your get on top of your put it should work. The problem seems to be that the static clause resolves your request before it gets to your endpoint, so if you do this:
app.get('/counselling/triageadmin/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
the path to the get will attempt to be matched before you're routed to your static files.
Ideally you would want to have your rest endpoints under a different namespace, i.e. /api but if you decide to keep your setup, this should help.
I think your routes might be conflicting with each other. From the express documentation at: http://expressjs.com/en/4x/api.html#app.use
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
});
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome');
});
Thus, your route '/counselling/triageadmin/getTable' will never be reached, because your route '/counselling/triageadmin/' is intercepting it, responding with static resources.
To solve this, try organizing your routes in a way that puts all of your API requests at a different subfolder, like '/api'. So your getTable endpoint would be located at: '/api/counselling/triageadmin/getTable/' or something like that.
I'm also learning the MEAN stack and I stumbled upon your question since I had the opposite problem. I wanted it to respond with an HTML instead of a JSON
this line of code MAKES it respond with an HTML
res.send(JSON.stringify(result["recordset"]));
(I tried res.send("<h3 HTML T_T </h3>");) and it did send and HTML
however, if you try
res.json(String(req.params.id)); <= Notice the res.json instead of res.send
It responds with a JSON :)
I hope this helped

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.

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).