Node.js:代理站点如何处理相对 URL?
我在 Node 中创建了一个相对简单的代理,它允许我下载页面并显示它们。这很好,尽管一些脚本、链接、表单和图像似乎已损坏,因为它们指向相关文件。作为一个项目,我试图创建一个功能齐全的网络代理。
像 Proxify 这样的网站如何解决这个问题?
方案参考:
var app = require('express').createServer();
var request = require('request'),
sys = require('sys'),
fs=require('fs');
app.get('/url', function(req, res){
console.log(req.query.link);
request({ uri: req.query.link,
headers: {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0"}
}, function (error, response, body) {
if (error && response.statusCode !== 200) {
console.log('Error when contacting google.com')
}
res.send(body, {"Content-type": "text/html"});
res.end();
});
});
I've created a relatively simple proxy in Node, which allows me to download pages and display them. This is fine, although some scripts, links, forms and images seem to be broken since they are pointing to relative files. As a project I'm trying to create a fully functional web proxy.
How do sites like Proxify solve this problem?
Program for reference:
var app = require('express').createServer();
var request = require('request'),
sys = require('sys'),
fs=require('fs');
app.get('/url', function(req, res){
console.log(req.query.link);
request({ uri: req.query.link,
headers: {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0"}
}, function (error, response, body) {
if (error && response.statusCode !== 200) {
console.log('Error when contacting google.com')
}
res.send(body, {"Content-type": "text/html"});
res.end();
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在,您的代码仅代理 html 文件,客户端直接从真实站点获取其余部分。您将需要使用类似 Node jQuery 的东西来替换文档中的所有 src/href 以使它们通过您的代理,同时您可以检查它们是否是相对的以及它们是否前置当前 url然后创建您的代理网址。
Right now your code is only proxying the html file, and the client is grabbing the rest directly from the real site. You'll want to use something like node jQuery to replace all src/href in the document to make them go through your proxy, and at the same time you can check if they're relative or not and if they are prepend the current url and then create your proxy url.