我可以帮助您解决问题的第一部分,就像@JohnnyHK 所说,这是一个广泛的问题。我在这里要解释的是如何使用node.js加载网页的原始数据并在json对象中表达并发送回客户端。
让我们从我们的要求开始
我们的目标是在浏览器中输入如下网址,获取页面的原始数据(html源):http://localhost:8080/www.yahoo.com
-
http://localhost:8080 - 我们的 node.js/express 服务器在哪里运行
-
www.yahoo.com - 我们要从中获取源的站点的 DOMAIN - http:// 不需要
现在,到服务器代码
请注意,这是一个非常简单/基本的服务器,因此您最好自己改进它
var http = require('http'); // the http `native` module of node
var express = require('express'); // the express :)
var app = express(); // creating the server...
app.enable("jsonp callback"); // enable jsonp callbacks
app.listen(8080); // listening to port 8080.
app.get('/:domain', function(req, res){ // each request to the pattern `http://localhost:8080/URL_HERE
// building the http `options` param
var options = {
host: req.params.domain, // the host will be the `domain` we sent
port: 80, // the port the website is running on (basically post 80)
path: '/', // the path, now, this is important to pages inside
// the website, if you want the source of
// `http://www.website.com/path/to/page.html` you better
// transfer `/path/to/page.html` as another param to the
// request and put it here
method: 'GET' // well, you know...
}
var buffer = ''; // i'm creating a buffer to hold the data
http.get(options, function(httpres){ // creating the request with a callback function
httpres.setEncoding('utf8'); // setting the encoding for the data...
httpres.on('data', function(chunk){ // listening to the `data` event, each chunk will get into this function
buffer += chunk; // saving the data...
});
httpres.on('end', function(){ // listening to the `end` event will be raised when we got all the raw data
res.json({ // this is it, now we are sending a response to the client as a json
success: true,
data: buffer
});
});
});
});
就是这样,您可以将此解决方案与jsonp 结合使用,您就可以开始了...
客户端
让我们使用 jQuery jsonp 请求来获取数据:
function loadData (domain) {
$.ajax({
url: 'http://localhost:8080/' + domain
cache: false,
dataType: 'jsonp',
jsonp: 'callback',
data: { },
success: function (response) {
if(response.success) {
console.log(response.data); // `response.data` holds the html
// data from the server, do what you want :)
}
}
});
}
你问题的第二部分是关于如何在客户端显示数据,我的建议是创建一个 iframe 并将原始数据注入其中,你会遇到一些问题(比如相关的 css 和 javascript 文件路径)但我希望你现在有一个起点......
干杯:)
更新
还有一件事..这个例子只适用于http协议网站...如果你想从https网站获取数据,你需要使用https模块而不是http( var https = require('https'); ) 并在 options 中,使用端口 443...