gpt4 book ai didi

node.js - 在nginx下运行nodejs

转载 作者:IT老高 更新时间:2023-10-28 23:08:41 27 4
gpt4 key购买 nike

我目前正在尝试使用在 nginx 中连接运行 nodejs 的 nginx 和 nodejs。我遇到的问题是我目前不在根目录(/)下运行 nodejs,而是在/data 下运行,因为 nginx 应该正常处理静态请求。 nodejs 不必知道它在/data 下,但它似乎是必需的。

换句话说。我希望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', function(req, res, params) {
res.writeHead(200, { 'Content-type': 'text/plain' });
res.end('app.get /data/test');
});
};

最佳答案

我认为这个解决方案可能会更好(如果您使用 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')
});

关于node.js - 在nginx下运行nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8121676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com