In this code I want to create a request object to download a wikipedia page.
This is how I tried to do it:
var https = require('https');
var fs = require('fs');
var options = {
hostname: 'en.wikipedia.org/',
port: 443,
path: '/wiki/George_Washington'
};
var req = https.request(options, function(res) {
var responseBody = "";
res.setEncoding("UTF-8");
res.on('data', function(chunk) {
responseBody += chunk;
});
res.on('end', function() {
fs.writeFile('wikipedia.md', responseBody, function(err) {
if(err) {
throw err;
}
});
});
});
req.on('error', function(err) {
if(err) {
console.log('Problem with request ', err);
}
});
req.end();
But i received the following error:
Problem with request { [Error: getaddrinfo ENOTFOUND en.wikipedia.org/ en.wikipedia.org/:443]
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'en.wikipedia.org/',
host: 'en.wikipedia.org/',
port: 443 }
Could it be that I got the wrong port number? Or somthing is wrong with my routes?
Your hostname:
hostname: 'en.wikipedia.org/',
contains a trailing slash. Remove it:
hostname: 'en.wikipedia.org',
and your code works fine.
Related
I am trying call multiple API in request but getting below exception when I am running the application.
Node Version: 10.15.2
NPM Version: 6.4.1
I already set proxy at global level using npm config set http-proxy in the terminal
Exception:
C:\Data\NPM\Testing>node server.js
node.js application starting...
Node HTTP server is listening
One
two
{ Error: getaddrinfo ENOTFOUND mocktarget.apigee.net mocktarget.apigee.net:80
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'mocktarget.apigee.net',
host: 'mocktarget.apigee.net',
port: 80 }
{ Error: getaddrinfo ENOTFOUND httpbin.org httpbin.org:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'httpbin.org',
host: 'httpbin.org',
port: 443 }
Code:
var http = require('http');
var async = require('async');
var request = require('request');
console.log('node.js application starting...');
var svr = http.createServer(function (req, resp) {
async.parallel({
one: function (callback) {
console.log("One");
request('http://mocktarget.apigee.net/json', function (error, response, body) {
console.log(error);
});
},
two: function (callback) {
console.log("two");
request('https://httpbin.org/headers', function (error, response, body) {
console.log(error);
});
}
}, function (err, results) {
console.log(results);
});
});
svr.listen(9000, function () {
console.log('Node HTTP server is listening');
});
Please help me how to resolve this issue if anyone knows. Thank you.
I have created the following code which grabs a seralizedXmlFile object from an S3 bucket and pushes it to a api service. This returns FAIL with the logs showing
Error: getaddrinfo ENOTFOUND http://url
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
CODE:
const AWS = require('aws-sdk');
const https = require('http');
var s3 = new AWS.S3();
var un;
var pw;
var seralizedXmlFile;
let index = function index(event, context, callback) {
//for testing I have named the bucket and key
var params = {
Bucket: "bucket", //event.bucketName,
Key: "personnelData_50112404_635705766849654385.xml" //event.fileName
};
s3.getObject(params, function(data, err)
{
if (data)
{
let seralizedXmlFile = err.Body.toString('utf-8'); // Use the encoding necessary
console.log("objectData " + seralizedXmlFile);
}
});
var ssm = new AWS.SSM({region: 'ap-southeast-2'});
var paramsx = {
'Names' : ['/App/ServiceUsername', '/App/ServicePassword'],
'WithDecryption' : true
};
ssm.getParameters(paramsx, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {console.log('data: ' + JSON.stringify(data)); // successful response
console.log('password: ' + data.Parameters[0].Value);
console.log('username: ' + data.Parameters[1].Value);
pw = data.Parameters[0].Value;
un = data.Parameters[1].Value;
}
const req = https.request('http:/url/api/SyncPersonnelViaAwsApi/Get/5', (res) => {
res.headers + 'Authorization: Basic ' + un + ':' + pw;
let body = seralizedXmlFile;
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
console.log('returned res: ' + res);
callback(null, res);
});
});
req.end();
});
};
exports.handler = index;
I followed a Q and A I found on AWS Lambda: Error: getaddrinfo ENOTFOUND
and changed the code to
var params = {
host: "http://URL",
path: "/api/SyncPersonnelViaAwsApi/Get/5"
};
var req = https.request(params, function(res) {
let data = '';
console.log('STATUS: ' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
console.log("DONE");
console.log(JSON.parse(data));
but again firing the same error....does anyone have any idea what the issue is?
I have also tested the web service api through POSTMAN, so I can confirm it is working
Thank You
Try
host: "URL",
instead of
host: "http://URL",
Also, you're using the https library and your URL prefix is http:// but I think you can/should omit it altogether.
Error: getaddrinfo ENOTFOUND http://url
means client was not able to connect to given address. Please try specifying host without http:
var params = {
host: "URL",
path: "/api/SyncPersonnelViaAwsApi/Get/5"
};
I'm trying to call freecodecamp api #url https://forum.freecodecamp.org/c/getting-a-developer-job.json?
I am doing some analysis on the data, but when I call this service using 'request' npm package I am getting ssl error as follows:
error { Error: write EPROTO 140735782093632:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1500:SSL alert number 40
140735782093632:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:
at _errnoException (util.js:1022:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:867:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
Can somebody let me know what the issue is? A wget call pulls the data when provided with --ca-certificate option, also the webservice is giving data to postman without any certificate.
Here is my code:
import request from 'request';
import fs from 'fs';
const BASE_URL = 'forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1';
request.get(BASE_URL, {
port: 443,
agentOptions: {
ciphers: 'ALL',
ca: fs.readFileSync('./mycertfile.pem'),
secureProtocol: 'TLSv1_2_method'
},
strictSSL: false
})
.on('response', (response) => {
console.log('Response is ', response);
}).on('error', (err) => {
console.log('error', err);
});
I see no problems there except URI http:// is absent, in my environment i have node v10.5.0, and the slightly modified version of your script works well:
const request = require('request')
const BASE_URL = 'https://forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1'
request.get(BASE_URL, { json: true }, (err, res, body) => {
if (err) throw('error', err);
console.log('JSON object is => ', body);
})
outputs to console:
JSON object is => { users:
[ { id: 117390,
username: 'anthony2025',
....
Im currently writing some code to read a WebAPI.
C:\Users\XXXX\XXXX\XXXX>node bot.js
undefined:1
SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\Users\XXXX\XXXX\XXXX\bot.js:82:20)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Here is my code
var http = require('http');
var options = {
host: 'backpack.tf',
port: 80,
path: '/api/IGetPrices/v4?key="personalapikey"',
method: 'GET'
};
http.request(options, function(res){
var body = '';
res.on('data', function(chunk){
body+=chunk;
});
res.on('end', function(){
var price = JSON.parse(body);
console.log(price);
});
}).end();
I am very new to node.js and coding in general. But I have tried like 3 other ways of trying to get this to work. I'm out of ideas
You can try and add the following things to your code to make it more robust and error proof, check for the response code, check the body isn't empty, print body to the logs to make sure it's a valid JSON, and parse the body in a try catch in case the API respond with invalid JSON.
var http = require('http');
var options = {
host: 'backpack.tf',
port: 80,
path: '/api/IGetPrices/v4?key="personalapikey"',
method: 'GET'
};
http.request(options, function(res){
var body = '';
res.on('data', function(chunk){
body+=chunk;
});
res.on('end', function(){
if (res.statusCode == 200) { // Check the status code returned in the response
try { // Add try catch block to handle corrupted json in response
if (body != '') { // Check that the body isn't empty
console.log(body); // Print the body to check if it's actually a valid JSON
var price = JSON.parse(body);
console.log(price);
} else {
console.log('Body is empty');
}
} catch (err) {
console.log(err);
}
} else {
console.log('Status code: ' + res.statusCode);
}
});
}).end();
I'm getting this error and unable to fix this.
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
var http = require('http');
var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};
var callback = function(response){
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
console.log(body);
});
}
var req = http.request(options, callback);
req.end();