节点.js 返回 301 重定向的请求

Node.js Requests returning 301 redirects

本文关键字:请求 重定向 js 返回 节点      更新时间:2023-09-26

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

但是,无论我尝试发出什么请求(即使我只是查询 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>

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

我的代码如下:

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/');

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

对我来说

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

require('http');

require('https');

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

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

基本上,您可以浏览标头并自己处理重定向,也可以为此使用少数模块之一。 我使用过"请求"库,并且自己运气很好。 https://github.com/mikeal/request

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

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

我写了同样的代码:

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

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

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

您必须在URL之前添加"www."才能获取HTML内容,否则会出现301错误。

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