javascript Node.js 请求返回 301 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11061118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:58:45  来源:igfitidea点击:

Node.js Requests returning 301 redirects

javascriptnode.jshttpnginxhttp-redirect

提问by dxu

I'm brand new to node.js, but I wanted to play around with some basic code and make a few requests. At the moment, I'm playing around with the OCW search (http://www.ocwsearch.com/), and I'm trying to make a few basic requests using their sample search request:

我是 node.js 的新手,但我想尝试一些基本代码并提出一些请求。目前,我正在尝试使用 OCW 搜索 ( http://www.ocwsearch.com/),并尝试使用他们的示例搜索请求提出一些基本请求:

However, no matter what request I try to make (even if I just query google.com), it's returning me

但是,无论我尝试提出什么请求(即使我只是查询 google.com),它都会返回给我

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/0.7.65</center>
</body>
</html>

I'm not too sure what's going on. I've looked up nginx, but most questions asked about it seemed to be asked by people who were setting up their own servers. I've tried using an https request instead, but that returns an error 'ENOTFOUND'.

我不太确定发生了什么。我查过 nginx,但大多数关于它的问题似乎都是由正在设置自己的服务器的人提出的。我尝试使用 https 请求,但返回错误“ENOTFOUND”。

My code below:

我的代码如下:

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');

    var options = {
      host:'ocwsearch.com',
      path:
      '/api/v1/search.json?q=statistics&contact=http%3a%2f%2fwww.ocwsearch.com%2fabout/',
      method: 'GET'
    }  


    var req = http.request(options, function(res) {
      console.log("statusCode: ", res.statusCode);
      console.log("headers: ", res.headers);
      res.on('data', function(d) {
            process.stdout.write(d);
      });
    });
    req.end();

    req.on('error', function(e) {
      console.error(e);
    });


}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Sorry if this is a really simple question, and thanks for any help you can give!

对不起,如果这是一个非常简单的问题,感谢您提供的任何帮助!

采纳答案by Brad

The problem is that Node.JS's HTTP Request module isn't following the redirect you are given.

问题是 Node.JS 的 HTTP 请求模块没有遵循您给出的重定向。

See this question for more: How do you follow an HTTP Redirect in Node.js?

有关更多信息,请参阅此问题: 如何在 Node.js 中跟踪 HTTP 重定向?

Basically, you can either look through the headers and handle the redirect yourself, or use one of the handful of modules for this. I've used the "request" library, and have had good luck with it myself. https://github.com/mikeal/request

基本上,您可以查看标头并自己处理重定向,或者为此使用少数模块之一。我使用过“请求”库,并且我自己也很幸运。 https://github.com/mikeal/request

回答by kendotwill

For me the website I was trying to GET was redirecting me to the secure protocol. So I changed

对我来说,我试图获取的网站正在将我重定向到安全协议。所以我改变了

require('http');

to

require('https');

回答by James

var http = require('http');

var find_link = function(link, callback){

  var root =''; 

  var f = function(link){

    http.get(link, function(res) {

      if (res.statusCode == 301) {
        f(res.headers.location);
      } else {
        callback(link);
      } 

    });
 }

  f(link, function(t){i(t,'*')});
}   

find_link('http://somelink.com/mJLsASAK',function(link){
  console.log(link);
});

function i(data){
  console.log( require('util').inspect(data,{depth:null,colors:true}) )
}

回答by Brian SP

This question is old now, but I got the same 301 error and these answers didn't actually help me to solve the problem.

这个问题现在很老了,但我遇到了同样的 301 错误,这些答案实际上并没有帮助我解决问题。

I wrote the same code:

我写了同样的代码:

var options = {
    hostname: 'google.com',
    port: 80,
    path: '/',
    method: 'GET',
    headers: {
       'Content-Type': 'text/plain',
    }
};

var http = require('http');

var req = http.request(options, function(res) {
    console.log('STATUS:',res.statusCode);
    console.log('HEADERS: ', JSON.stringify(res.headers));
    res.setEncoding('utf8');

    res.on('data', function(chunk) {
        console.log(chunk);
    });
    res.on('end', function() {
        console.log('No more data in response.');
    });
});

req.on('error', function(e) {
    console.log('problem with request: ', e.message);
});
console.log(req);

req.end();

so after some time I realized that there's a really tiny mistake in this code which is hostname part:

所以一段时间后我意识到这段代码中有一个非常小的错误,即主机名部分:

 var options = {
     hostname: 'google.com',
     ...

you have to add "www." before your URL to get html content, otherwise there would be 301 error.

您必须添加“www”。在你的 URL 之前获取 html 内容,否则会出现 301 错误。

var options = {
     hostname: 'www.google.com',