Socket Hangup Error in Node.js on using https - javascript

I'm trying to use HTTP GET method via Nodejs using secure connection https. Here is my code:
var https = require('https');
https.globalAgent.options.secureProtocol = 'SSLv3_method';
var options = {
host: 'my_proxy_address',
port: 3128,
path: 'https://birra-io2014.appspot.com/_ah/api/birra/v1/beer',
method: 'GET',
headers: {
accept: '*/*'
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
When i run this, i get an error:
{ [Error: socket hang up] code: 'ECONNRESET', sslError: undefined }
I cannot use HTTP because appspot requires https.
Please help!
Thanks in advance.

Try the following code. (Its working for me)
var https = require('https');
var options = {
port: 443,
host: 'birra-io2014.appspot.com',
path: '/_ah/api/birra/v1/beer',
method: 'GET',
headers: {
accept: '*/*'
}
};
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error('ERROR object ==>' + e);
});

Related

Getting no data with express/react/next.js data request using http

Problem:
I am trying to request data from http://localhost:3000/auth/sendUserData using http, but I am getting no data/response (no console.logs).
What I'm using:
Next.js/React, Node (backend server), getInitialProps (Next.js).
Code:
Userdata.js
const http = require("http");
const Userdata = {};
Userdata.getUserData = async function(){
let url = `http://${process.env.HOST}:${process.env.PORT}/auth/sendUserData`
console.log(url);
const options = {
host: process.env.HOST,
port: process.env.PORT,
path: '/auth/sendUserData'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on("data", function(chunk) {
console.log("BODY: " + chunk);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
};
export default Userdata;
http://localhost:3000/auth/sendUserData
{
_id: "5c5521f823a5d183945fd62f",
name: "Saddy",
steamID: "76561198151478478",
__v: 0
}
Problem was with backend authentication since it was rendered on the server and not on the client, causing the session to be lost

make a https OPTIONS request which returns a JSON body

How can i make a https OPTIONS request to an existing REST endpoint using node.js?
When I use postman with the OPTIONS request method i get back the JSON body of all the existing endpoints.
I followed the node.js docs and here is what i am doing -
var options = {
hostname: host,
port: 443,
path: urlPar,
method: 'OPTIONS'
};
var req = https.request(options, function(res){
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
console.log("returned data", d);
});
});
req.end();
req.on('error', function(e){
console.error("error thrown", e);
});
But i get this error for the request -
{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }
Is there another way how to do this?

How to send form data in node.js

I am able to get to the server but unable to post my form data.
How should I post the form data with the https request?
I am using form-data library for form-data, and https request for post call.
When I run the following code, I am able to reach the service, but the service gives a response saying that the form data is not submitted.
var https = require('https');
var FormData = require('form-data');
//var querystring = require('querystring');
var fs = require('fs');
var form = new FormData();
connect();
function connect() {
username = "wr";
password = "45!"
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
var options = {
hostname: 'trans/sun.com',
port: 443,
path: '/transfer/upload-v1/file',
method: 'POST',
rejectUnauthorized: false,
headers: {
'Authorization': auth,
'Content-Type': 'application/json',
//'Content-Length': postData.length
}
};
form.append('deviceId', '2612');
form.append('compressionType', 'Z');
form.append('file', fs.createReadStream('/Mybugs.txt'));
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
//console.log("headers: ", res.headers);
res.setEncoding('utf8');
res.on('data', function(d) {
console.log(d)
});
});
req.write(form + '');
req.end();
req.on('error', function(e) {
console.error(e);
});
}
You never link your form to your request. Check this example provided with the form-data documentation
var http = require('http');
var request = http.request({
method: 'post',
host: 'example.org',
path: '/upload',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});

Unable to POST data in node.js script

I am requesting a https post method with a data but my data is not going with the request and thats why service is giving error, so how can i change my code so that it will get to the server , here is my code
var https = require('https');
var querystring = require('querystring');
connect();
function connect(){
var postData = querystring.stringify({
'application': 'QF2',
'client': 'COMMAND',
'userId': 'devicexxx',
'operation': 'at-cmd',
'payload': 'dfdfdfdf',
'messageId': '123e454567-e89b-12d3-a456-42665544'
});
var options = {
hostname: 'cus.inco.com',
port: 443,
path: '/portal/action/dev',
method: 'POST',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length
}
};
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
//console.log("headers: ", res.headers);
res.setEncoding('utf8');
res.on('data', function(d) {
console.log(d)
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
}
You need to write() your POST data before you end the request.
req.write(postData);
req.end();

Steps to send a https request to a rest service in Node js

What are the steps to send a https request in node js to a rest service?
I have an api exposed like (Original link not working...)
How to pass the request and what are the options I need to give for this API like
host, port, path and method?
just use the core https module with the https.request function. Example for a POST request (GET would be similar):
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
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();
The easiest way is to use the request module.
request('https://example.com/url?a=b', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Note if you are using https.request do not directly use the body from res.on('data',... This will fail if you have a large data coming in chunks. So you need to concatenate all the data and then process the response in res.on('end'. Example -
var options = {
hostname: "www.google.com",
port: 443,
path: "/upload",
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
};
//change to http for local testing
var req = https.request(options, function (res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end',function(){
console.log("Body :" + body);
if (res.statusCode !== 200) {
callback("Api call failed with response code " + res.statusCode);
} else {
callback(null);
}
});
});
req.on('error', function (e) {
console.log("Error : " + e.message);
callback(e);
});
// write data to request body
req.write(post_data);
req.end();
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );
Since there isn't any example with a ´GET´ method here is one.
The catch is that the path in the options Object should be set to '/' in order to send the request correctly
const https = require('https')
const options = {
hostname: 'www.google.com',
port: 443,
path: '/',
method: 'GET',
headers: {
'Accept': 'plain/html',
'Accept-Encoding': '*',
}
}
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
console.log('headers:', res.headers);
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(`Error on Get Request --> ${error}`)
})
req.end()
The example using 'GET' method is good but it can also be used with constant variables in TypeScript/Node.js setup. If that's the case, the functions on('error') and end() have to be defined outside of the https.request function.
const https = require('https')
const options = {
hostname: 'www.google.com',
port: 443,
path: '/',
method: 'GET',
headers: {
'Accept': 'plain/html',
'Accept-Encoding': '*',
}
}
const request = https.request(options, res => {
const callback = (data: string) => {
process.stdout.write(`response data: ${data}`);
}
res.on('data', callback)
})
request.on('error', error => {
console.error(`Error on Get Request --> ${error}`)
})
request.end()

Categories