【问题标题】:how to use node.js and php on the same port如何在同一个端口上使用 node.js 和 php
【发布时间】:2013-09-19 05:01:29
【问题描述】:

我已经在端口 12234 上安装了 node.js、socket.io 和 express.js,效果非常好。但是现在我想在该端口(12234)上的页面上使用 php,但我不知道该怎么做。有人有解决办法吗?

对不起,我的英语不好,我是荷兰人,英语不太好。

【问题讨论】:

    标签: php node.js express socket.io port


    【解决方案1】:

    您不能在同一个端口上运行两个应用程序。最简单的做法是将 HTTP 请求代理到 PHP,在另一个端口上运行,并将其他请求代理到 Socket.IO,在另一个端口上运行。

    这是一个使用http-proxy 的示例。请注意,这不适用于 flashsockets 和 XHR 长轮询。

    var httpProxy = require('http-proxy')
    
    var server = httpProxy.createServer(function (req, res, proxy) {
      proxy.proxyRequest(req, res, {
        host: 'localhost',
        port: // whatever port PHP is running on
      });
    })
    
    server.on('upgrade', function (req, socket, head) {
      server.proxy.proxyWebSocketRequest(req, socket, head, {
        host: 'localhost',
        port: // whatever port Socket.IO is running on
      });
    });
    
    server.listen(80);
    

    或者,您可以将 Express 路由路由到 PHP。例如,如果 PHP 在 8080 端口上运行:

    app.get('/', function(req, res) {
      // send a HTTP get request
      http.get({hostname: 'localhost', port: 8080, path:'/', function(res2) {
        // pipe the response stream
        res2.pipe(res);
      }).on('error', function(err) {
        console.log("Got error: " + err.message);
      });
    });
    

    【讨论】:

    • 如果您在端口 8080 上运行 PHP CMS,那么此路由会命中 CMS 生成的所有子页面吗?还是这只适用于索引页面,需要为每个页面提供一个路由?
    • 这实际上会将所有路由映射到 PHP 服务器上的 /。您必须根据传入的 req.url 来映射请求。
    • 不工作TypeError: Cannot read property 'protocol' of undefined
    【解决方案2】:

    您可以通过 nginx 让 node.js 作为上游运行。假设您使用的是 nginx 和 php5-fpm。

    upstream node {
        server 127.0.0.1:8080;
    }
    
    location / {
        proxy_pass  http://node;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_redirect off;
        proxy_buffering off;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
    
    location ~ \.php$ {
        index index.php;
        root   /var/www;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-28
      • 2012-08-27
      • 2013-03-09
      • 1970-01-01
      • 2016-11-19
      • 2016-02-08
      • 1970-01-01
      • 2015-01-07
      • 2017-06-09
      相关资源
      最近更新 更多