【发布时间】:2020-08-07 05:30:41
【问题描述】:
我有一个 Node.js 应用程序,前端使用 React。当我在本地开发它时,我将项目放在http://localhost/app子目录下,api在/api下,我使用的端口是5000。一切正常。这是我设置的方式:
对于 Node.js,我使用它来设置前端目录和路由器:
const indexRouter = require('./routers')
app.use('/api', indexRouter) //to set API path
app.use('/app', express.static('public'))
服务器正在监听 5000。
对于 React,我将 package.json 更新为:
"homepage": "/app",
"proxy": "http://localhost:5000/"
对于 Axios 请求,我在请求路径的开头添加基本变量并将其设置为 '/api'
这在我的本地主机上都很好。但是,当我使用 Nginx 将其部署到 AWS 时,我无法使 API 请求成功。
使用 Nginx,我从
更新原始位置块location / {
try_files $uri $uri/ = 404;
}
到
location /app {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
当我转到/root/app 时,我可以看到 React 的主页(我将 React 构建文件复制到 Node js 公共文件夹中)。但是,它无法获得请求成功。在我的localhost上可以看到,请求路径是http://localhost:3050/api/login,但是live sever请求路径是http://domain_name/login,不知道为什么服务器不能去@ 987654327@ 请求。
我希望有人可以帮助我。
【问题讨论】:
-
您是否在部署到生产环境之前构建了您的 React 应用程序?使用 npm 还是纱线?
-
是的。我通过 create-react-app 创建了 React 应用,然后运行 yarn run build 创建 build 文件夹并将这些文件全部复制到 Node js 的 public 文件夹中。
标签: node.js reactjs nginx amazon-ec2