NodeJS http post data empty - node.js

I am not able to get the data in the http post method of express nodejs.I am posting data from angular2. When i inspect in the network section of chrome, the payload is visible but the same data is received blank at app.post method.Please help me.
angular2 code
this.headers = new Headers();
this.headers.append('Content-Type', 'x-www-form-urlencoded');
let body = JSON.stringify({name:"Lionel Messi"});
return this.http
.post('http://localhost:8081/save',body
,this.headers);
}
nodejs code
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/save', function (req, res) {
console.log("Got a POST request for the homepage");
console.log(req.body);// output - {}
res.send('Hello POST');
})
Network Section in Chrome....payload is proper

alert method in node.js will not work . You need to use console.log("Hello");
Second thing is to get body data , use req.body.name
My way of writing code is like below and it works
$http({
method: 'POST',
url: 'http://localhost:8081/save',
data: {name:"Lionel Messi"}
})
.success(function(data) {
return data
})
.error(function(error) {
// handle error
});
Other way you can try is:
$http.post('http://localhost:8081/save', {name:"Lionel Messi"})
.then(function(data) {return data})
.catch(function() {console.log("Error Occured");});

You can do it like this-
Suppose you have sent username and password from your browser by post method.
app.post("/ url,function(request,response)
{ var username=request.body.username;
var password=request.body.password;})

Related

Request.body is empty object even after sending a fetch post request with body

Fetch request through an HTML page.
I want to post formData object to the server which is hosted locally.
let formData={
name:document.getElementById('name').value,
question:document.getElementById('question').value
}
let response=await fetch('http://localhost:5000/',{
method:'POST',
mode:'no-cors',
headers:{'Content-Type':'application/json'},
body:JSON.stringify(formData)
}).then((res)=>console.log(res)).catch((err)=>console.log(err))
})
The req.body gives an empty object, I also tried using body-parser but it didn't work either.
//--------app.js-------------
const express = require('express');
const app=express();
const port=process.env.PORT || 5000;
app.use(express.json());
app.get('/',(req,res)=>{
res.send('im alive')
})
app.post('/',(req,res)=>{
console.log(req.body);
res.json({status:"okay"});
})
app.listen(5000,()=> console.log('Listening at '+port));
The mode:'no-cors' is messing things up. This mode leads to only selected content type headers to be sent.
Allowed list. allowed content types
headers: [
['Content-Type', 'application/x-www-form-urlencoded'],
['Content-Type', 'multipart/form-data'],
['Content-Type', 'text/plain'],
]
So you have 2 options left.
1.Remove 'no-cors' mode.
2.Use content type:application/x-www-form-urlencoded. You would need additional code to convert the json, but it can get complicated.Json to url encoded
Make sure you wait for the data before printing.
fetch('http://127.0.0.1:3000/')
.then(async data => {
const res = await data.json() // data is a promise here
console.log(res)
})

Getting exception on webhook from Stripe

I'm trying to set up a webhook from Stripe to handle the payment_intent.succeeded event, but I get an exception. This is my code from the Node backend (I have extracted all the relevant parts I hope. Let me know if anything else is needed):
const stripeWebHookSecret = 'whsec_WA0Rh4vAD3z0rMWy4kv2p6XXXXXXXXXX';
import express from 'express';
const app = express();
app.use(bodyParser.urlencoded({ extended:true }));
app.use(bodyParser.json());
app.use(session({ <some params here> }));
const openRouter = express.Router();
registerOpenPaymentRoutes(openRouter);
app.use('/open', openRouter);
And the implementation of registerOpenPaymentRoutes looks like this:
export const registerOpenPaymentRoutes = (router) => {
router.post('/payment/intent/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
let signature = req.headers['stripe-signature'];
try {
let event = stripe.webhooks.constructEvent(req.body, signature, stripeWebHookSecret);
switch(event.type){
case 'payment_intent.succeeded':
let intent = event.data.object;
res.json({ message: 'Everything went smooth!', intent });
default:
res.status(400).json({ error: 'Event type not supported' });
}
}
catch (error){
res.status(400).json({ message: `Wrong signature`, signature, body: req.body, error });
}
});
}
So far so good.When I fire a test webhook event from the Stripe dashboard, I hit the endpoint, but get the result from the catch block. The error message is as follows:
No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing"
I'm returning the signature with the error message as well as you see above, and the signature looks like this:
"t=1557911017,v1=bebf499bcb35198b8bfaf22a68b8879574298f9f424e57ef292752e3ce21914d,v0=23402bb405bfd6bd2a13c310cfecda7ae1905609923d801fa4e8b872a4f82894"
As far as I understand from the documentation, what is needed to get the raw request body as mentioned are the bodyParser.raw({type: 'application/json'})argument to the router that I already have there.
Can anyone see the missing part?
It's because you've already set your express app to use the bodyParser.json() middleware, which clashes with the bodyParser.raw() middleware you set up in your webhook route.
If you remove the app.use(bodyParser.json()); line your webhooks will work as intended, but then the rest of your routes won't have a parsed body, which isn't ideal.
I suggest adding a custom middleware to choose the bodyParser version based on route. Something like:
// only use the raw bodyParser for webhooks
app.use((req, res, next) => {
if (req.originalUrl === '/payment/intent/webhook') {
next();
} else {
bodyParser.json()(req, res, next);
}
});
Then explicitly use the bodyParser.raw() middleware on the webhook routes.
I came up with the very same problem, the answer above gave me an idea on how to solve it but didn't make the gig for me, so thanks for pointing me in the right direction.
I share the way it worked for me to bring the body raw without too much effort
I just add in my index.js after
app.use(bodyParser.urlencoded({ extended: false }));
this
app.use(
bodyParser.json({
verify: function (req, res, buf, encoding) {
req.rawBody = buf;
},
})
);
app.use(
bodyParser.urlencoded({
extended: false,
verify: function (req, res, buf, encoding) {
req.rawBody = buf;
},
})
);
And then on the function where I needed a raw body I used:
router.post("/webhook",express.raw({ type: "application/json" }),async (req, res) => {
const sig = req.headers["stripe-signature"];
const body = req.rawBody; //here I got the raw body
});
And that was enough to pass the (in this case) stripe validation
Hope to be helpful to somebody!
Have a great coding!

node js POST not getting data using React

I am submitting a form and the following gets called...
handleLogin(){
fetch('http://localhost:8080', {
method: 'post',
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});
}
It makes a POST request to my restAPI. The request works, but the data is not passed...
app.post('/', function(req, res, next) {
console.log(req.body.username);
....
This prints out undefined, meaning password and username are not passed through the call. What am I doing wrong?
Express by default doesn't parse the body of the request. In order to enable parsing, you will need to use a middleware such as body-parser. You can find some information in the express docs.
Also, the client side needs to indicate that it's sending json data. That can be achieved with the Content-Type header. There is a pretty good tutorial about fetch() here. You can jump directly to the Request Headers section which is relevant for your question.
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
const PORT = process.env.PORT || 7070;
const BASEURL = process.env.BASEURL || 'http://localhost/7070';
app.use(bodyParser.urlencoded({extended:true}));
app.listen(PORT, function() { console.log('Server running on'+BASEURL);
});

Sending/handling GET requests in typescript using Express, Request and Node.js

I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".
This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.
import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
})
app.listen(3000);
I've tried both of the following but both of them say that body is undefined.
import request = require("request");
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
this.config = JSON.parse(body);
})
request(`/config`, function(err, res, body) {
this.config = JSON.parse(body);
});
Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.
UPDATE
If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
console.log("response => "+JSON.parse(body));
return JSON.parse(body);
})
Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.
Hopefully this will save you hours of debugging...
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/config`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}
I dont't know if you have posted whole of your server's code, it seems like you missed app.listen(port) so that your server cannot be started up correctly.
Also, if you added if (error) { console.log(error); } at the first line of the callback function of request, you'll find it print an error: [Error: Invalid URI "/config"]
And that's why the body is always undefined: You have to give the full url such like http://localhost:xxxx to request.
In short:
Your server didn't listen to a specific port. app.listen(5678)
Your client didn't know the complete url. request('http://localhost:5678/config', (...)=>{...})

expressJS request object

I'm trying to go through the expressJS tutorial. This is my server code:
var express = require('express');
var app = require('express').createServer();
app.use(express.bodyParser());
app.post('/', function(request, response) {
console.log('Inside the post request!');
console.log(request);
response.send(resquest.body);
});
app.listen(3000);
and here is the POST request I am simulating:
$.ajax({
url: 'http://localhost:3000',
type: 'POST',
datatype: 'json',
data: {hello: 1},
success: function () {
console.log('Success!');
},
error: function () {
console.log('Error!');
}
});
The problem is that the request object does not seem to contain data: {hello: 1}. Instead it is a big mess of under-the-hood parameters. Am I doing something stupid?
I think that since you're not setting the content type to multipart/form-data it's assuming form encoded data. In which case, you'd set your data in your ajax request to be:
data: 'hello=1'
Set your content-type to: application/x-www-form-urlencoded
Access it via request.body.hello. It's been awhile, but try that.
You've written resquest.body instead of request.body; when you fix that, you'll be able to use request.body.data as others have pointed out.
You need to look at request.body. When you do request.body, you get {hello: 1}.

Resources