NodeJS Error: header too long at Object.createSecureContext - node.js

I am trying to call the REST API with PFX & PassPhrase, but each time I getting 'header too long' error.
My certificate file size is 11kb. Below snippet is working fine for other REST API without pfx, but no success with pfx
var options = {
hostname: '<hostname>',
port: 443,
path: '/',
method: 'POST',
pfx: fs.readFileSync(<pfx file path>),
passphrase: '<passphrase>',
json: { 'Request': 'My Custom Req'}
};
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(e);
});
I have ran my application with following command; but still problem persists:
node --max-http-header-size=819200 .\restPost.js
The REST API is perfectly working and I have tested the same using Postman and .NET Core web client solutions.
Need your help to fix the issue in NodeJS

Related

IBM - Creating a VPC using API with Node.js

I have a Node.js application which currently allows the user to provision a Digital Ocean Droplet. However, I'm now trying to migrate over to IBM Cloud and instead want to provision a Virtual Server.
The issue I'm having is I have no experience working with APIs. Digital Ocean has its own NPM package acting as a wrapper over the Digital Ocean API bit I can't find an equivalent for IBM Cloud. I've been looking through the VPC API documentation and I have gone through the entire process of creating a Virtual Server using the terminal and I've successfully provisioned a Virtual Server.
Now, I'm trying to get these cURL requests to work in Node.js. I'm starting with just the simple GET images API to try and print the available images. The command looks like this:
curl -X GET "https://eu-gb.iaas.cloud.ibm.com/v1/images?version=2019-10-08&generation=1" \
-H "Authorization: *IAM TOKEN HERE*"
I've read over the Node HTTP documentation and so far I've converted this command to look like this:
const http = require('http')
const options = {
hostname: 'https://eu-gb.iaas.cloud.ibm.com',
port: 80,
path: '/v1/images?version=2019-10-08&generation=1',
method: 'GET',
headers: {
'Authorization': '*IAM TOKEN HERE*'
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();
However, when I run the JS file, I get the following error:
problem with request: getaddrinfo ENOTFOUND https://eu-gb.iaas.cloud.ibm.com https://eu-gb.iaas.cloud.ibm.com:80
Can someone please explain to me the error, where I'm going wrong, and how I can fix this issue?
Many thanks in advance,
G
try as below:
const https = require('https');
const options = {
hostname: 'eu-gb.iaas.cloud.ibm.com',
port: 443,
path: '/v1/images?version=2019-10-08&generation=1',
method: 'GET',
headers: {
'Authorization': 'Bearer <IAM TOKEN HERE>'
}
};
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', (e) => {
console.error(e);
});
req.end();
The protocol http:// shouldn't be included in the host field, also, it is recommended the use of https.

nodejs, make https request to backend server

Using https request, I was trying to connect to backend server using the below documentation guide:
http://nodejs.org/api/https.html#https_https_request_options_callback
function getHttpsReq (request, response)
{
var options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
rejectUnauthorized: false,
strictSSL: false,
agent: false,
method: 'GET'
}
https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
var data = '';
res.on('data', function(d) {
process.stdout.write(d);
data += data + d;
});
res.on('end', function() {
console.log("Done");
response.end(data);
});
});
}
But when I am trying this, it is throwing the below error:
Error: 140735290610048:error:0607907F:digital envelope
routines:EVP_PKEY_get1_RSA:expecting an rsa
key:../deps/openssl/openssl/crypto/evp/p_lib.c:288:
$ node --version
v0.8.15
Please let me know what I need to do extra?
What you need are the certificates to your domain.
This can be added using the below code.
key: fs.readFileSync('/etc/apache2/ssl/domain.key'),
cert: fs.readFileSync('/etc/apache2/ssl/domain.crt')
to your options.
The certificates can be obtained using a trusted authority or you can use self signed certificates. But self signed certificates would generate an error on client's side if it is not added to the trusted certificates in client's machine.

Access rest api using nodejs

I am trying to access opencorporates.com and using their REST API.
I got this code from How to make remote REST call inside Node.js? any CURL?. But it is not fetching any data. I tried wget on the url and it worked perfectly fine.
app.js
var https = require('http');
var optionsget = {
host : 'opencorporates.com',
port : 8080,
path : '/v0.2/companies/search?q=barclays+bank&jurisdiction_code=gb',
method : 'GET'
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
var reqGET = https.get(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('GET result:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
Because Node runs asynchronously, the returned data is broken into chunks.
The .on('data') event returns a portion of the data, which you then need to stitch/append back to a variable. You can then capture the complete output with .on('end').
See this example for more info: Why is node.js breaking incoming data into chunks? (#vossad01's answer)
That said, #SilviuBurcea's suggestion to use request is a much simpler way of handling http requests so you don't have to write and handle all of this yourself.
Try using request module. https://github.com/mikeal/request It's the http module on steroids.
Tried running the code locally, and first there is a capitalization error
var reqGET = https.get(optionsget, function(res) {
reqGet.end();
Second, the web address was not working at the address, nor with secure
var optionsget = {
host : 'api.opencorporates.com',
port : 80,
path : '/v0.2/companies/search?q=barclays+bank&jurisdiction_code=gb',
method : 'GET'
};
Its worth noting that if you wanted to actually use https, you would need to change the require line
var https = require('https');
This is fully functional version for your reference:
var http = require('http');
var optionsget = {
host : 'api.opencorporates.com',
port : 80,
path : '/v0.2/companies/search?q=barclays+bank&jurisdiction_code=gb',
method : 'GET'
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
var reqGet = http.get(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
buffer='';
res.on('data', function(d) {
//console.info('GET result:\n');
//process.stdout.write(d);
buffer += d.toString();
//console.info('\n\nCall completed');
});
res.on('end', function() {
console.info('GET result:\n');
console.log(buffer);
console.info('\n\nCall completed');
});
});
reqGet.on('error', function(e) {
console.error(e);
});
reqGet.end();

Twitter Streaming API - Node.js returning unauthorised error (OAuth)

I'm attempting to connect to Twitters Streaming API over OAuth using http.get although I'm having a slight problem.
The script keeps returning unauthorised
The code I'm using follows, can anybody tell me if I'm missing something stupid or my headers are incorrect.
var https = require('https');
var options = {
host: 'stream.twitter.com',
path: '/1.1/statuses/filter.json?track=bieber',
method: 'GET',
headers: {
authorization: '
OAuth
oauth_consumer_key = "",
oauth_nonce = "",
oauth_signature = "",
oauth_signature_method = "HMAC-SHA1",
oauth_timestamp = "",
oauth_token = "",
oauth_version = "1.0"
'
}
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
});
});
req.on('error', function(e) {
console.log('Oops... ' + e.message);
});
req.write('data\n');
req.write('data\n');
req.end();
The problem I had here was that the OAuth request was NOT being signed, which ment the authorisation was failing.
OAuth is a complicated process and it's best to use a library or NPM module that has already been developed.
The particular NPM I used in this instance was node-oauth
try this:
var options = {
host: 'stream.twitter.com',
path: '/1.1/statuses/filter.json?track=bieber',
method: 'GET',
auth : "YOUR_ID:YOUR_PASS"
};
var https = require('https');
https.get(options,function(res){
res.on("data",function(trunk){
//YOUR CODE
}).on("end",function(){
//YOUR CODE
}).on("error",function(e){
//YOUR CODE
});
}

Using http.request in Node.JS while passing an API key

I am currently fiddling around with Node.JS to try to create a package for PostageApp to be able to send emails through our API.
To start, I am using the following code to test out how Node.JS can best interface with our API, but it doesn't seem to want to pass along the API key that I have attached as part of the headers.
var http = require('http');
function onRequest(request, response) {
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
var options = {
host: 'api.postageapp.com',
path: '/v.1.0/get_account_info.json',
method: 'POST',
headers: { "api_key" : "MY API KEY HERE" }
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.end();
console.log("Request sent!");
I pulled this together using various examples and what not - it's not pretty, I know. However, using HTTPS, I finally got it to hit our API and get a response:
{"response":{"status":"unauthorized","message":"Invalid or inactive API key used","uid":null}}
The only conclusion I can come up with is that the API key is not getting passed along, and I would appreciate any help as to how to make that happen.
Thanks!
Here's an example of code I have used to call web APIs with a key in the header:
var api = http.createClient(80, 'api.example.org');
var request = api.request('GET', '/api/foo',
{
'host': 'api.example.org',
'accept': 'application/json',
'api-key': 'apikeygoeshere'
});
request.on('response', function (response) {});
request.end();

Resources