加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

node.js – 在nginx下运行nodejs

发布时间:2020-12-13 21:28:36 所属栏目:Nginx 来源:网络整理
导读:我正在尝试nginx和nodejs与连接运行nodejs代理在nginx.我的问题是,我目前不在根(/)下运行nodejs,而是在/ data下,因为nginx应该正常处理静态请求. nodejs不应该知道它在/数据下,但似乎是必需的. 换一种说法.我想要nodejs“想”它运行在/.那可能吗? nginx配置

我正在尝试nginx和nodejs与连接运行nodejs代理在nginx.我的问题是,我目前不在根(/)下运行nodejs,而是在/ data下,因为nginx应该正常处理静态请求. nodejs不应该知道它在/数据下,但似乎是必需的.

换一种说法.我想要nodejs“想”它运行在/.那可能吗?

nginx配置:

upstream app_node {
    server 127.0.0.1:3000;
}

server {
...

     location /data {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;

            proxy_pass http://app_node/data;
            proxy_redirect off;
    }
}

nodejs代码:

exports.routes = function(app) {
    // I don't want "data" here. My nodejs app should be able to run under
    // any folder
    app.get('/data',function(req,res,params) {
            res.writeHead(200,{ 'Content-type': 'text/plain' });
            res.end('app.get /data');
    });
    // I don't want "data" here either
    app.get('/data/test',{ 'Content-type': 'text/plain' });
            res.end('app.get /data/test');
    });
};
最佳答案
我认为这个解决方案可能会更好(如果你使用像Express或类似的东西,使用“中间件”逻辑):

添加一个中间件函数来改变URL

rewriter.js

module.exports = function temp_rewrite() {
  return function (req,next) {
    req.url = '/data' + req.url;
    next();
  }
}

在你的Express应用程序中这样做:

的app.config

// your configuration
app.configure(function(){
  ...
  app.use(require('./rewriter.js').temp_rewrite());
  ...
});

// here are the routes
// notice you don't need to write '/data' in front anymore all the time

app.get('/',function (req,res) {
  res.send('This is actually site.com/data/');
});

app.get('/example',res) {
  res.send('This is actually site.com/data/example')
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读