dxu*_*dxu 8 javascript http nginx http-redirect node.js
我是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>
Run Code Online (Sandbox Code Playgroud)
我不太确定发生了什么事.我查了一下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/');
Run Code Online (Sandbox Code Playgroud)
对不起,如果这是一个非常简单的问题,感谢你提供任何帮助!
对我来说,我试图获取的网站将我重定向到安全协议。所以我改变了
require('http');
Run Code Online (Sandbox Code Playgroud)
到
require('https');
Run Code Online (Sandbox Code Playgroud)
问题是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}) )
}
Run Code Online (Sandbox Code Playgroud)