如何通过添加其他参数来重定向传入的 URL 请求 [英] How to redirect incoming URL requests by adding additional parameters
问题描述
问题:我的服务器应用程序收到一个传入的 HTTP 请求.请求是这样的:http://example.com?id=abc.我需要解析这个请求,修补额外的 URL 参数并调用一个托管的 html 文件.所以:
Problem: I get an incoming HTTP request to my server application. The request is something like this : http://example.com?id=abc. I need to parse this request, patch additional URL parameters and call a hosted html file. So:
http://example.com?id=abc => http://example.com:8080/temp.html?id=abc&name=cdf.
所以客户端应该看到 temp.html
So the client should see temp.html
代码如下:
function onRequest(request,response) {
if(request.method =='GET') {
sys.debug("in get");
var pathName = url.parse(request.url).pathname;
sys.debug("Get PathName" + pathName + ":" + request.url);
var myidArr = request.url.split("=");
var myid = myidArr[1];
//Call the redirect function
redirectUrl(myid);
}
http.createServer(onRequest).listen(8888);
function redirectUrl(myid) {
var temp='';
var options = {
host: 'localhost',
port: 8080,
path: '/temp.html?id=' + myid + '&name=cdf',
method: 'GET'
};
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) {
temp = temp.concat(chunk);
});
res.on('end', function(){
return temp;
});
});
req.end();
return temp;
}
尽管这是解决此问题的非常愚蠢的方法,但我确实在 res.end() 回调中看到了响应.如何将此传播到父调用函数 onRequest ?
Even though this is a really stupid way of going about this issue, I do see the response in the res.end() callback. How to propagate this to the parent calling function onRequest ?
是否有一种更简单的方法可以仅使用 node 来做到这一点?我知道有一些方法可以提供静态 html 文件.但是,我需要将 URL 参数传递给 temp.html - 所以我不确定如何执行此操作.
Is there a simpler way of doing this just using node ? I know that there are ways to serve static html files. However, I need to pass URL parameters to temp.html - so I'm not sure how to do this.
推荐答案
只是想知道更简单的重定向是否能达到目的:
Just wondering if a simpler redirect would serve the purpose:
function onRequest(request,response) {
if(request.method =='GET') {
sys.debug("in get");
var pathName = url.parse(request.url).pathname;
sys.debug("Get PathName" + pathName + ":" + request.url);
var myidArr = request.url.split("=");
var myid = myidArr[1];
var path = 'http://localhost:8080/temp.html?id=' + myid + '&name=cdf';
response.writeHead(302, {'Location': path});
response.end();
}
这篇关于如何通过添加其他参数来重定向传入的 URL 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!