的 临时解决方案: 强> 对我来说并不理想,但它现在必须到期,因为我至少可以配置它。我正在使用以下命令启动节点服务器:
node app2.js /data
处理根节点的代码:
exports.routes = function(app) { var me = this; // get the root path me.proxyRootPath = process.argv[2]; // using the proxyRootPath to answer to the correct request app.get(me.proxyRootPath, function(req, res, params) { res.writeHead(200, { 'Content-type': 'text/plain' }); res.end('app.get /data'); }); // using the proxyRootPath to answer to the correct request app.get(me.proxyRootPath + '/test', function(req, res, params) { res.writeHead(200, { 'Content-type': 'text/plain' }); res.end('app.get /data/test'); }); };
我通常这样做:
的 nginx配置: 强>
upstream app_node { server 127.0.0.1:3000; } server { ... location /data/ { ... proxy_pass http://app_node rewrite ^/data/(.*)? /$1 break; } }
的 node.js app: 强>
app.get('/something', function(req, res, next) { ... });
然后,从外面的世界,我可以提出如下的请求 http://my-host-name/data/something?someKey=someValue ,nginx将传递给node.js应用程序,该应用程序只会将其视为 /something?someKey=someValue (因为网址被重写了)。
http://my-host-name/data/something?someKey=someValue
/something?someKey=someValue
我知道这不是唯一的方法,而是更好的方法,因为我始终尊重“的理念” 做一件事并做得好的事情 “。在这里,Nginx擅长重写URL,而Node.js擅长处理请求本身。
解决方案:
编写应用程序以在命令行中查找目录。运行应用程序时,在命令行上传递目录。
编写应用程序以查找特定环境变量中的目录。运行应用程序时首先设置环境变量。
编写应用程序以假定其当前目录是目标目录。运行应用程序时首先切换到目录。
编写应用程序以升级目录树以查找已知文件(例如,升级目录查找 ./app2.js ,然后找到该文件的目录是目标目录)。
./app2.js
我认为这个解决方案可能会更好(如果你使用像Express或类似的东西使用“中间件”逻辑):
添加中间件函数来更改URL如此
的 rewriter.js 强>
module.exports = function temp_rewrite() { return function (req, res, 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', function (req, res) { res.send('This is actually site.com/data/example') });