Keep Getting Bad Request from HTTP.request in Node.js

情到浓时终转凉″ 提交于 2019-12-13 15:14:04

问题


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!


回答1:


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 :)




回答2:


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);
});


来源:https://stackoverflow.com/questions/17690402/keep-getting-bad-request-from-http-request-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!