尝试下载网页时出现错误请求错误

时间:2016-05-25 11:19:55

标签: node.js httprequest httpresponse

我正在尝试下载网页,并编写了以下代码:

var https = require("https");

var options = {
    hostname : "stackoverflow.com",
    port : 443,
    path : "questions/18867185/socket-hang-up-error-during-request",
    method : "GET"
};

var req = https.request(options, function(res) {
    var responseBody ="";

    console.log("Response from server started..\n");
    console.log("Status Code : " + res.statusCode + "\n");
    console.log("\n\n\n Headers : %j", res.headers);
    res.setEncoding("UTF-8");

    res.on("data",function(data) { 
        console.log("--Data-- " + data);
        responseBody += data;
    });

    res.on("end",function() {
        console.log("Download complete\n");
        console.log(responseBody);
    });
});

req.on("error",function(err) {
    console.log("Error reportted " + err);
});

req.end();

但我总是得到400 | Bad Request错误!这可能是什么原因?

回应:

Response from server started..

Status Code : 400

 Headers : {"server":"cloudflare-nginx","date":"Wed, 25 May 2016 11:05:23 GMT","content-type":"text/html","content-length":"177","connection":"close"}
--Data-- <html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare-nginx</center>
</body>
</html>

Download complete

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare-nginx</center>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

从&#34; questions / 18867185 / socket-hang-up-error-during-request&#34;更改您的路径属性to&#34; / questions / 18867185 / socket-hang-up-error-during-request&#34;。注意开头的斜线。我在更改之前重现了您的错误。希望这会有所帮助。