问题描述
前端设置了服务代理,正常访问后端接口,配置如下:
vite.config.ts
文件export default defineConfig({ // 配置代理,解决跨域 server: { cors: true, proxy: { '/api': { target: 'http://localhost:8080/', // 127:测试请求的地址0720 changeOrigin: true, // 开启跨域 rewrite: (path) => path.replace(/^\/api/, ''), // 将其置为空, 发请求时去掉api } } } })
request.ts
文件const service = axios.create({ baseURL: import.meta.env.VITE_API_URL, timeout: 10000, >headers: { 'Content-Type': 'application/json;charset=utf-8' } });
.env
文件
VITE_API_URL = /api
项目部署服务器之后,访问接口就报错404
解决
-
进入Nginx配置文件:
cd /etc/nginx/
-
进入nginx.conf配置文件进行查看:
vim nginx.conf
-
本项目的主要配置是在
sites-enabled
,进行查看编辑,:q!
退出编辑 — Nginx反向代理
location /api/ {
proxy_pass http://127.0.0.1:8000/; # 转发规则
proxy_set_header Host $proxy_host; # 修改转发请求头,让8000端口应用收到真实请求
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
- 查看是否编辑成功:
nginx -t
- 重启nginx:
systemctl restart nginx
- 查看nginx状态:
systemctl status nginx