node.js - 如何通过添加其他参数来重定向传入的URL请求

Pra*_*ara 3 redirect node.js

这更像是一个概念性的问题 - 所以请光临我.

问题:我收到了一个传入的HTTP请求到我的服务器应用程序.请求是这样的:http://xyz.com?id = abc.我需要解析此请求,修补其他URL参数并调用托管的html文件.所以:

http://xyz.com?id=abc => http://xyz.com:8080/temp.html?id=abc&name=cdf.

所以客户端应该看到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;
}
Run Code Online (Sandbox Code Playgroud)

尽管这是解决此问题的一种非常愚蠢的方法,但我确实在res.end()回调中看到了响应.如何将它传播到父调用函数onRequest?

有没有更简单的方法来做这个只是使用节点?我知道有办法提供静态html文件.但是,我需要将URL参数传递给temp.html - 所以我不知道如何做到这一点.

任何帮助将不胜感激.

alm*_*pal 12

只是想知道更简单的重定向是否可以达到目的:

  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();
    }
Run Code Online (Sandbox Code Playgroud)

  • 别客气.请你接受答案. (2认同)