I just installed Node.js and perhaps I'm missing something but I'm trying a simple http.request and get nothing but 400 responses. I've tried several hosts with no luck. I installed Node from their site, this didn't work, so I uninstalled and installed via Homebrew and get the same output of "400". I'm specifically wondering if there's something I need to change on my Mac to allow Node to send requests.
OSX 10.8.4 Node 0.10.13 Homebrew 0.9.4
var http = require("http");
var req = http.request({
host: "http://google.com"
}, function(res){
if (res.statusCode === 200) console.log(res);
else console.log(res.statusCode);
});
req.on("error", function(err){
console.log(err);
});
req.end();
I appreciate any help. Thanks!
The http:// in your host is confusing things. Try switching it to "www.google.com". It's an http request, no need to repeat yourself :)
Have you tried taking the http://
out of your host
parameter? I often use the url
utility for things like this. It'll automatically parse a url into the correct parts to pass to http.request
.
var url = require('url'),
link = url.parse('http://www.google.com/');
var req = http.request({
host: link.hostname,
path: link.path,
port: link.port
}, function(res){
if (res.statusCode === 200) console.log(res);
else console.log(res.statusCode);
});
Also, I'd make sure to catch the error event as well in case that is throwing an error. From the docs:
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
If you just need a GET
response you can also use http.get
instead. From the docs:
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With