3

我想通过 nginx 将某些参数传递给 nodejs。

虽然我仍然使用 fastcgi,但我可以这样做:

fastcgi_param   SCRIPT_FILENAME         $document_root$fastcgi_script_name;
fastcgi_param   PATH_INFO               $fastcgi_script_name;

现在我基本上在为 node.js 搜索完全相同的功能

这将是我当前的配置:

server {
    # ... other stuff ...

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        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://node;
        proxy_redirect off;

        # pass any parameter here
    }

}

upstream node {
        server  127.0.0.1:8080;
}

我怎样才能做到这一点?- 而且,如何读取 node.js 中传递的值?

4

2 回答 2

5

直接解决您的问题的简短答案,在您的 nginx 配置中,添加如下行:

proxy_set_header X-My-Custom-Param-1 $whatever_variable_you_want_to_pass;

并在您的快速路由处理程序函数中读取它,

req.get('X-My-Custom-Param-1');

但是,如果您解释了您要解决的更大问题以及您认为需要通过的具体值,我们可以提供具体帮助。您很可能在解决已解决的问题时表现不佳。我还没有看到任何需要这种设置的实际用例。

于 2013-07-05T20:32:48.297 回答
0

默认情况下将传递任何参数,您只需在节点中自行处理路由。

请查看express.js,因为它允许使用正则表达式(如果需要)定义非常灵活的路由。
请记住,params快递不同于query数据(PHP 中的 $_GET)。由于query数据在 URL 中的问号之后,但params在路由中定义。
例如:

app.get('/user/:id', function(req, res, next) {
  res.send({
    params: req.params
    query: req.query
  }); // will respond with json object with 'id'
});

然后测试它,使用 url:http://example.com/user/23?foo=bar&hello=world
它将输出:

{
  params: {
    id: 23
  },
  query: {
    foo: 'bar',
    hello: 'world'
  }
}
于 2013-07-05T09:54:45.573 回答