如何在本地主机中使用Nginx运行快递服务器?
我想在本地主机中使用Nginx运行Express服务器。可能吗?如果可能的话,我该如何实现?
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Server listening at http://localhost:${port}`))
回答如下:如果要使用nginx作为Express的反向代理,则可以按照以下步骤配置服务器:
server {
listen 80 default_server;
server_name _;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://localhost:3000; #port where you are serving your express app.
}
}
您应该在/etc/nginx/sites-available/default
中进行配置
更改配置文件后,检查脚本中是否没有错误:
$sudo nginx -t
预期结果应该是:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
配置正常后,您应该使用以下命令重新启动nginx实例:
$sudo nginx -s reload
正确重新加载后,断言您的节点/ express服务器正在运行。现在,如果您访问http://localhost
,则应该在http://localhost:3000
]中查看正在监听的内容
Nginx应该为您的实例提供服务,当您停止节点/表达时,您应该会看到默认错误502。