node js http post request save cookie - node.js

I am calling an http post request(login request from another 3rd party server) from node and want to save the cookie for future http requests.
var options = {
host: 'hostname.com',
port: '80',
path: '/login.php',
method: 'POST'
};
var data = qs.stringify({
uname: "validUsername",
password: "validPassword"
});
var req = http.request(options, function(response) {
console.log(response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
// console.log('Cookies: ' + response.getHeader("Set-Cookie"));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(data);
req.end();
How can i access and save the cookie from the response sent by the requested server?

You should be able to get the header with response.headers['set-cookie'];.
If you need to actually parse them, you could use a module like cookie (what Express uses) or cookiejar.

Related

How can I make an HTTPS POST request in node.js?

How can I make an HTTPS POST request to an API. My code doesn't work, because it cannot find the resource.
API Documentation: https://applymagicsauce.com/documentation at Authentication
My code, which doesn't work
var https = require('https');
var options = {
host: 'https://api.applymagicsauce.com',
port: 443,
path: '/auth',
method: 'POST'
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
error message: STATUS: 415
HEADERS: {"server":"nginx/1.15.10","date":"Fri, 09 Aug 2019 18:22:48 GMT","content-type":"application/json;charset=UTF-8","transfer-encoding":"chunked","connection":"close","x-content-type-options":"nosniff","x-xss-protection":"1; mode=block","cache-control":"no-cache, no-store, max-age=0, must-revalidate","pragma":"no-cache","expires":"0","strict-transport-security":"max-age=15724800; includeSubDomains","x-frame-options":"DENY"}
BODY: {"timestamp":"2019-08-09T18:22:48.981+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'application/octet-stream' not supported","path":"/auth"}
Looks like your host includes a path, but you're also providing a path.

getaddrinfo ENOTFOUND when making a post request using node.js

I want to send a POST request to my server using Node.js
function login(email, company_code, password){
var options = {
hostname: '266fd57b.ngrok.io',
path: '/v1/manager/sign_in',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
'email': email,
'company_code': company_code,
'password': password
}
};
var req = https.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('{"string": "Hello, World"}');
req.end();
return true;
}
But I keep getting error:
getaddrinfo ENOTFOUND 266fd57b.ngrok.io 266fd57b.ngrok.io:443
I tried all the fixes found on the Internet but nothing worked.
Oh my god this is because I have not entered billing account for google.
Dialogflow needs a credit card number to work.

nodejs paypal pdt return 302

I'm using nodejs and express. This is my code that is run on the return from Paypal. I only get a 302 errors in response from Paypal. I saw a couple examples that use ssl:// instead of https:// but nodejs yells saying that its not a valid protocol for the https module. Does anyone have a working nodejs script for PDT and IPN?
var purchaseID = req.query.tx;
var atoken = MYAuthToken;
var postDataArray = {'cmd':'_notify-synch','tx': purchaseID, 'at': atoken}
var postData = JSON.stringify(postDataArray);
console.log(postData);
var options = {
hostname: 'www.sandbox.paypal.com',
port: 443,
path: '/cgi-bin/webscr',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, function(res) {
console.log('STATUS: '+ res.statusCode);
console.log('HEADERS: '+ JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('BODY: '+chunk);
});
res.on('end', function() {
console.log('No more data in response.')
});
});
req.on('error', function(e) {
console.log('problem with request: '+e.message);
});
req.write(postData);
req.end();
});
This
You're missing Accept: */* header. Also, JSON.stringify is not application/x-www-form-urlencoded. Here is some working code for you to build based on:
var request = require('request');
var endpoint = 'www.sandbox.paypal.com';
var options = {
form: {
cmd: '_notify-synch',
tx: tx,
at: auth
},
headers: {
Accept: '*/*'
}
};
request.post('https://' + endpoint + '/cgi-bin/webscr', options, function(e, r, body) {
return console.log(body);
});
Try just posting without the JSON
var postData = "cmd=_notify-synch,at=" + at + ",tx=" + tx;
I've edited a couple of times as i ran into issues. I'm new to node so just hacking out a solution with trial and error. Your post moved me towards the solution. So here is postData that works with your code. It's nice to see the FAIL ans SUCCESS messages come through. Note .. need the &'s
var postData = "cmd=_notify-synch&at=" + at + "&tx=" + tx;

NodeJS HTTP Post - GZip

I have a NodeJS client that is similar to
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Is there any way to make the data element in the req.write gzipped at all?
To send a compressed request, compress the data into a zlib buffer, then write that as your output:
var zlib = require('zlib');
var options = {
hostname: 'www.example.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {'Content-Encoding': 'gzip'} // signal server that the data is compressed
};
zlib.gzip('my data\ndata\n', function (err, buffer) {
var req = http.request(options, function(res) {
res.setEncoding('utf8');// note: not requesting or handling compressed response
res.on('data', function (chunk) {
// ... do stuff with returned data
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(buffer); // send compressed data
req.end();
});
That should send a gzipped request to the server and get a non-compressed response back. See the other answers to this question for handling a compressed response.
You can gzip a stream using the native zip library: http://nodejs.org/api/zlib.html
var zlib = require('zlib');
var gunzip = zlib.createGunzip();
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {'Accept-Encoding': 'gzip'}
};
var req = http.request(options);
gunzip.on('data', function (buf) {
body += buf.toString();
});
gunzip.on('end', function() {
console.log(body);
// do whatever you want to do with body
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
gunzip.end();
});
req.pipe(gunzip);
More info on zlib library: http://nodejs.org/api/zlib.html

Which type of errors captured on req.on(''error)

i am using node.js i write a small code
var http = require('http');
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
i have to send post requests for starting i am making get requests that why no http.get().in this request i am getting 404 response code which is also an error.but not captured in req.on('error') .i want to know which kind of error this methd captures ??
From http.request documentation:
If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.
So probably that event is only emitted when there is an error at the protocol/connection level.
You can then process HTTP errors on the connect call:
var req = http.request(options, function(res) {
if (res.statusCode == "404"){ ... }
else if (...) {
...
} else { // everything ok
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
...
}
});

Resources