【发布时间】:2021-12-05 23:45:09
【问题描述】:
在链接缩短网站上工作。站点在我的 localhost 生产环境中按预期工作,但在我部署的 Digital Ocean Ubuntu Linux 服务器上启用 Nginx 后,我似乎无法获得带有查询参数的 Express GET 路由。
Node.js/Express GET 路由:
router.get("/:code", async (req, res) => {
try {
const url = await Url.findOne({ urlCode: req.params.code });
if (url) {
return res.redirect(url.longUrl);
} else {
return res.status(404).json("no url found");
}
} catch (error) {
console.error(error);
res.status(500).json("server error");
}
});
Nginx 配置文件(etc/nginx/sites-available/default):
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
server_name myname.com www.myname.com;
location / {
proxy_pass http://localhost:3000/;
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-Forwarded-For $remote_addr;
proxy_cache_bypass $http_upgrade;
}
如果我将 localhost 端口更改为我的 Express 服务器 (7777),则 GET 路由将使用 URL 查询参数(即:http://example.com/random8chars),但不会加载 React 前端。
按照当前配置(端口 3000/React 服务器),到“/:code”的 Postman GET 路由返回所需的结果,但是当我在 Chrome 的 URL 栏中输入转换后的链接时,它会返回默认的启动页面。事实上,当我在 Chrome 中输入除我的站点名称之外的任何扩展名时,它总是显示默认启动页面。我知道这是 Nginx 的一个问题,但我似乎无法让它工作。
整天都在努力,但无济于事。发现多个 Stack Overflow 线程涉及该主题,但没有任何效果。我尝试向 Nginx 配置文件添加第二个位置路由,但无济于事。我尝试过的一个例子:
location /:code {
proxy_pass http://localhost:7777/:code;
}
请帮忙!我被困住了,感觉我离这个工作很近了。我将非常感谢任何有关解决此问题的见解。谢谢。
【问题讨论】:
标签: node.js reactjs express nginx routes