如何在同一个快速服务器上运行客户端和API?

时间:2016-06-07 21:00:59

标签: express

我有一个使用API​​端点的React / Redux应用程序。我目前在一台服务器上渲染React / Redux客户端,而在另一台服务器上渲染我的API - 都使用express。如何在同一台服务器上运行它们。我是否只为我的客户端提供静态目录并添加GET / POST /等。像这样的服务器:

//...

app.use(express.static('dist'));

app.get('/api/users', function(req, res) {
    //...
  })

app.post('/api/users', function(req, res) {
    //...
  })

const PORT = process.env.PORT || 3000;

app.listen(PORT, function() {
  console.log(`Listening on port ${PORT}...`);
});

非常感谢任何和所有帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

您建议的内容应该正常工作,Express documentation中概述了这一点,但如果您要提供静态文件,我建议将它们置于{{3}之后反向代理。 Nginx在提供静态文件方面非常棒,如果您决定稍后使用HTTPS,那么您只需要为运行Nginx的机器提供证书,其余的通信可以通过HTTP完成。

基本上你安装Nginx并设置你的配置看起来像这样:

upstream api_pool {
    server localhost:3000;
    # feel free to add as many other servers to this pool as you'd like
}

server {
    listen       80;
    server_name  localhost;

    root /www/static_stuff;

    location / {
    }

    location /api {
        proxy_pass http://api_pool;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache_bypass $http_upgrade;
    }
}

重新启动Nginx以使配置更改生效,将所有静态内容放在/ www / static_stuff(或您决定制作根目录的任何内容)中,然后在端口3000上启动快速服务器。

现在,我们假设您将名为style.css的文件放入/ www / static_stuff。将Web浏览器指向localhost / style.css将提供文件/www/static_stuff/style.css。将Web浏览器指向localhost / api / some_express_route就像将Web浏览器指向localhost:3000 / some_express_route。

警告!我没有尝试过这个配置文件,但是如果你决定采用Nginx路线它并不起作用,请告诉我,我很乐意创建一个测试环境来帮助你运行

相关问题