Making an HTTP request using node.js throws EAFNOSUPPORT - node.js

I'm trying to make a simple HTTP GET request using node.js, but I'm running into trouble using node.js v0.3.4-pre (i.e. compiled from HEAD as of this morning). Here's my code:
var cli = require('cli');
var http = require('http');
var url = require('url');
cli.parse();
cli.main(function(args, opts) {
this.debug(args[0]);
var siteUrl = url.parse(args[0]);
var site = http.createClient(siteUrl.port, siteUrl.host);
console.log(siteUrl);
var request = site.request("GET", siteUrl.pathname, {'host' : siteUrl.host})
request.end();
request.on('response', function(response) {
response.setEncoding('utf8');
console.log('STATUS: ' + response.statusCode);
response.on('data', function(chunk) {
console.log("DATA: " + chunk);
});
});
});
Here's the error that I get:
node.js:68
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: EAFNOSUPPORT, Address family not supported by protocol family
at doConnect (net.js:499:19)
at Client.connect (net.js:652:30)
at Client._ensureConnection (http.js:1033:10)
at Client.request (http.js:1048:8)
at Object.<anonymous> (/Users/paul/Desktop/readify.js:16:21)
at /usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:995:18
at Object.main (/usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:1000:9)
at Object.<anonymous> (/Users/paul/Desktop/readify.js:10:5)
at Module._compile (node.js:359:32)
at Object..js (node.js:367:14)

Found the bug, siteUrl.port will be undefined unless the URL explicitly names a port. So, the solution is:
var site = http.createClient(siteUrl.port || 80, siteUrl.host);

var site = http.createClient(siteUrl.port, siteUrl.host);
should rather be
var site = http.createClient(siteUrl.port || 80, siteUrl.hostname);

The same error message appeared on my very old XPSP2-box for ANY connect()-attempts. E.g npm wasn't able to do anything, and simple http requests failed.
While trying to find a solution, this post appeared all over the place, but its not the same issue.
In my case it had to do with WSAIoctl(...) always returning WSAEOPNOTSUPP when querying for WSAID_CONNECTEX, which seemed strange. This led me to a post recommending doing a "netsh winsock reset" from the cmd, which fixed the problem!

Related

Programming the BeagleBone to turn on LED, Got NodeJS errors

The assignment is about embedded system. We are learning how to use BeagleBone Black and how we can use it to make small-size devices e.g., devices that can measure temperature and pulse.
A part of our first assignment is to follow this guide: https://randomnerdtutorials.com/programming-the-beaglebone-black-with-bonescript/
We need to make a server in Node JS and a index in html. The site provides button to control a LED light that is connected to a breadboard via BeagleBone Black.
I have connected the LED, pins and wires to the BeagleBone Black. Installed Ubuntu 18.14, NodeJS, npm socket.io and Bonescript(Script dedicated to BeagleBone).
I am not using Cloud 9 IDE to run the server.js and index.html.
But I use terminal in Ubuntu.
To start the server i use this command: node server.js
I tried for several days to make the server and index.html to run,
but I get this error or nothing happends:
/home/ubuntu/bonescript/server.js:42
var io = require('socket.io').listen(server);
^
[TypeError: require(...).listen is not a function
at Object.<anonymous> (/home/ubuntu/bonescript/server.js:42:31)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Can anyone help me pinpoint the problem? I am really stuck on this stage. Thanks.
index.html code:
<!DOCTYPE html>
<html>
<head>
<title>Home Automation Web Server with BeagleBone</title>
<script src = "/socket.io/socket.io.js" ></script>
<script>
// Establishing connection with server
var socket = io.connect();
// Changes the led state
function changeState(state){
if (state==1){
// Emit message changing the state to 1
socket.emit('changeState', '{"state":1}');
// Change led status on web page to ON
document.getElementById("outputStatus").innerHTML = "Status: ON";
}
else if (state==0){
// Emit message changing the state to 0
socket.emit('changeState', '{"state":0}');
// Change led status on web page to OFF
document.getElementById("outputStatus").innerHTML = "Status: OFF";
}
}
</script>
</head>
<h2>LED</h2>
<p id="outputStatus">Status</p>
<button type="button" onclick="changeState(1);">ON</button>
<button type="button" onclick="changeState(0);">OFF</button>
</div>
</body>
</html>
server.js code:
//Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');
// Create a variable called led, which refers to P9_14
var led = "P9_14";
// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);
// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
// requesting files
var file = '.'+((req.url=='/')?'/index.html':req.url);
var fileExtension = path.extname(file);
var contentType = 'text/html';
// Uncoment if you want to add css to your web page
/*
if(fileExtension == '.css'){
contentType = 'text/css';
}*/
fs.exists(file, function(exists){
if(exists){
fs.readFile(file, function(error, content){
if(!error){
// Page found, write content
res.writeHead(200,{'content-type':contentType});
res.end(content);
}
})
}
else{
// Page not found
res.writeHead(404);
res.end('Page not found');
}
})
}).listen(8888);
// Loading socket io module
var io = require('socket.io').listen(server);
// When communication is established
io.on('connection', function (socket) {
socket.on('changeState', handleChangeState);
});
// Change led state when a button is pressed
function handleChangeState(data) {
var newData = JSON.parse(data);
console.log("LED = " + newData.state);
// turns the LED ON or OFF
b.digitalWrite(led, newData.state);
}
// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));
I have same problem but solve it already the code on this website is based on older node version, you have to change the code on line
var io = require('socket.io').listen(server);
to
var io = require('socket.io')(server);
and edit variable or remove this line since newer node cant use .listen function twice (the code already use it on server var to open port 8888)
server.listen(console.log("Server Running ..."));
socket.io is an internal library, not an external one. Therefore, when you ran npm install socket.io, you downloaded something that is not the socket.io that you want.
Delete your node_modules, and remove socket.io from package.json, and reinstall bonescript via npm install. Then it should work.

Slack node js program running session shut down

Sorry to disturb. I am programming a Slack robot to reply user message by using the API
In the morning, it works totally okay. Then after I returned back from my office it just shut down and show me this error
Jiatongs-MacBook-Pro:news-bot jiatongli$ node index.js
Assertion failed: token must be defined
/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:105
throw e;
^
Error: not_authed
at _api.then.fail (/Users/jiatongli/Desktop/news-bot/node_modules/slackbots/index.js:46:33)
at Array.<anonymous> (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:773:56)
at callFns (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:24:35)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at _api.then.fail (/Users/jiatongli/Desktop/news-bot/node_modules/slackbots/index.js:46:19)
at Array.<anonymous> (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:773:56)
at callFns (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:24:35)
at process._tickCallback (internal/process/next_tick.js:61:11)
Jiatongs-MacBook-Pro:news-bot jiatongli$
I personally have no idea what is going on because it seems like the program itself do not have bug. What i miss?
Here is the code in my index.js file:
var SlackBot = require("slackbots");
var request = require("request");
var NewsAPI = require("newsapi");
var unirest = require("unirest");
var API_KEY = process.env.API_KEY;
var Slack_API = process.env.Slack_API;
// create a bot
var bot = new SlackBot({
token: Slack_API,
name: "aloha-ai"
});
bot.on("message", msg => {
switch (msg.type) {
case "message":
// we only want to listen to direct messages that come from the user
if (msg.channel[0] === "D" && msg.bot_id === undefined) {
getRandomTechNews(postMessage, msg.user)
}
break
}
})
const postMessage = (message, user) => {
bot.postMessage(user, message, {
as_user: true
});
}
const getRandomTechNews = (callback, user) => {
unirest.get("https://nuzzel-news-v1.p.rapidapi.com/news?count=10&q=product")
.header("X-RapidAPI-Host", "nuzzel-news-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", API_KEY)
.end(function (response) {
var newsJSON = response.body;
var news = "*Viral News* in product : \n\n\n\n";
for (i = 0; i < newsJSON.results.stories.length; i++) {
news += "_Excerpt:_ \n" + ">" + newsJSON.results.stories[i].excerpt + "\n"
news += "_Let's see the article!_ \n" + newsJSON.results.stories[i].url + "\n\n\n"
};
callback(news, user);
});
}
Your error message seems to indicate that your program is not authenticated with the Slack API: Error: not_authed
Since you are retrieving your API key and token from environment variables:
var API_KEY = process.env.API_KEY;
var Slack_API = process.env.Slack_API;
my guess is that you have started a new terminal session where you have not yet set that environment variable, or you are on a different computer where it is not set.
Before running your program, try exporting those variables from the command line:
export API_KEY=<my-api-key>
export Slack_API=<my-token>
If you have security concerns about your API keys showing up in your bash history you can do one of two things (these are examples of things that I do, but there are probably better, safer practices out there):
You can put an empty space before your command [space]export API_KEY=<my-api-key> instead of export API_KEY=<my-api-key>. This will make it so the command does not show up in your history.
You can put your export commands in a separate file called e.g., ~/.secrets and then run the command source ~/.secrets which will run your export commands.
Probably these will give you a sense of security rather than actual security though, since you can just echo the value of the environment variables, but I personally like taking one of these steps as an extra precaution.
i use this answer and can solve it.
Add a bot https://my.slack.com/services/new/bot and put the token
do you get token for your bot from above url:
did you set this ?

Unable to get response using node curl package on Nodejs

I'm using node curl to make a call to a WS. I wrote a simple function that just issues a request and I'm logging the response. This is how my server.js looks:
var http = require('http');
var curl = require('node-curl');
var config = require('./config');
var cfgObj = new config.config();
function start(port) {
function onRequest(request, response) {
console.log("Request received");
var options = {
VERBOSE: 1,
RAW: 1
};
curl.debug = 1;
curl.setDefaultOptions(options);
curl('www.google.com', function(err) {
console.log(this.body);
});
}
http.createServer(onRequest).listen(port);
}
cfgObj.getConfig(null, function(data) {
start(data.port);
});
cfgObj just contains the port number. It connected to the host properly and I even got HTTP 200 OK response:
[cURL 1] receive 2242 bytes
[cURL 1] receive succeeded.
But in the end, it says:
Bus error: 10
What does this mean?
The control never calls the function where I'm printing this.body. I even tried using http request but that gives me "socket hang up" error.
I have been unable to debug this issue. Any clues?
node-curl is broken, when I try to use it on my Mac I get the same error:
[2] 34539 bus error node test.js
(a bus error is an error which occurs when a program tries to write to an invalid memory location)
Here's a replacement for node-curl: https://github.com/mikeal/request

Node.js Beginner - Can't get past nodetuts tutorial number 2 - stdout and child process

I was trying to go through the tutorial nodetuts.com - tutorial 2 and unfortunatly could not get the example working, I'm very new to node.js and going through any tutorials I can get hold of. I understand that node.js is still beta and I figured that the code that makes this work is now obsolete. (This is the code):
var http = require('http');
var spawn = require('child_process').spawn;
http.createServer(function(request, response){
response.writeHead(200, {
'Content-Type' : 'text/plain'
});
var tail_child = spawn('tail', ['-f', 'test.txt']);
tail_child.stdout.on('data', function(data){
console.log(data.toString());
response.write(data);
});
}).listen(4000);
Anyway, determined to continue on I have been looking through the documentation on the node website and found this: http://nodejs.org/api/all.html#all_child_pid This is not exactly what I want (I want to complete that tutorial linked to up top) but I wanted to get something todo with child process working and incorperated that code into this:
var http = require('http');
var server = http.createServer(function(res, req){
res.writeHead(200);
res.end('testing');
var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
console.log('Spawned child pid: ' + grep.pid);
grep.stdin.end();
}).listen(4000);
Unfortunately when I refresh the page http://localhost:4000/ I get nothing and command prompt spits out: (I know it says writeHead is a problem, but it works fine in other examples - (like nodetuts - tutorial 1))
res.writeHead(200);
^
TypeError: Object #<IncomingMessage> has no method 'writeHead'
at Server.<anonymous> (Z:\Joseph Goss Folder\Google Drive\Code\javascript_first\nodejs_first\stdoutTest.js:20:6)
at Server.EventEmitter.emit (events.js:91:17)
at HTTPParser.parser.onIncoming (http.js:1785:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
at Socket.socket.ondata (http.js:1682:22)
at TCP.onread (net.js:404:27)
I wonder why I can't get this working, I'm obviously missing something but I don't know what, and I can't even get past tutorial number 2. :(
I'm running windows 7
I have also looked at this code Why does response.write appear to block my browser in Node.js? and his code doesn't work at all either.
You interchanged req and res in the function passed to createServer
var http = require('http');
var server = http.createServer(function(req, res){
res.writeHead(200);
res.end('testing');
var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
console.log('Spawned child pid: ' + grep.pid);
grep.stdin.end();
}).listen(4000);

now.js : "Object has no method" error message when trying to start server.js

I installed node.js and now.js successfully.
For now.js, this is how I did:
npm install now -g
npm install now (had to add this one. Without it, I get a "Cannot find now..." error message)
When I start the node server and provide a server.js file like this:
var httpServer = require('http');
httpServer.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Node is ok');
res.end();
}).listen(8080);
console.log('Server runs on http://xxxxx:8080/');
Everything is fine.
Now, I'm trying to add to this file a basic use of now.js:
var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);
everyone.now.logStuff = function(msg){
console.log(msg);
}
I create an index.html file in the same folder (for testing purposes)
<script type="text/javascript" src="nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function(){
now.logStuff("Now is ok");
});
</script>
This time, this is what I get on the terminal when starting the server:
Server runs on http://xxxxx:8080/
[TypeError: Object #<Object> has no method 'listeners']
TypeError: Object #<Object> has no method 'listeners'
at Object.wrapServer (/home/xxxx/node_modules/now/lib/fileServer.js:23:29)
at [object Object].initialize (/home/xxxx/node_modules/now/lib/now.js:181:14)
at Object.<anonymous> (/home/xxxx/server.js:10:22)
at Module._compile (module.js:444:26)
at Object..js (module.js:462:10)
at Module.load (module.js:351:32)
at Function._load (module.js:309:12)
at module.js:482:10
at EventEmitter._tickCallback (node.js:245:11)
Please keep in mind that I'm an absolute beginner.
Thank you for your help
'npm install -g' installs modules at a global level, often with the intent of providing system-wide binaries for terminal usage. Think Ruby Gems. If you want to include a module as part of your project you need to remove the -g.
Also, your httpServer variable is not your server but rather the http module. createServer() returns a server object which you want to capture with a variable to use in your nowjs.initialize() method as follows:
var http = require('http')
, now = require('now')
// Returns an Http Server which can now be referenced as 'app' from now on
var app = http.createServer(
//... blah blah blah
)
// listen() doesn't return a server object so don't pass this method call
// as the parameter to the initialize method below
app.listen(8080, function () {
console.log('Server listening on port %d', app.address().port)
})
// Initialize NowJS with the Http Server object as intended
var everyone = nowjs.initialize(app)

Resources