一,项目配置
我在 ip 为 192.168.31.177 的机器上使用 vue3 开发前端项目,项目中使用 axios 调用后端接口。
这是 axios 的配置:
import axios from 'axios';
const request = axios.create({
baseURL: 'http://192.168.31.177:8001',
// 设置请求头
headers: {},
// 设置超时时间
timeout: 2000,
});
// 请求拦截器
request.interceptors.request.use(
config => {
// 在发送请求之前做些什么
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 响应拦截器
request.interceptors.response.use(
response => {
if (response) {
// 响应数据为二进制流处理(数据导出)
if (response.data.data instanceof Blob) {
return response
}
const {code, msg} = response.data
if (code === 200) {
return Promise.resolve(response.data)
} else {
return Promise.resolve(response)
}
} else {
return Promise.reject(new Error('系统出错'))
}
},
function (error) {
// 对响应错误做点什么
// 比如:根据响应状态码,做不同的响应处理
console.log(error)
return Promise.reject(error)
}
)
export default request
这是页面中的请求:
axios.get('/api/getNumbers')
.then(res => {
ElMessage({
message: res.msg,
type: 'success'
})
}).catch(err => {
ElMessage({
message: err,
type: 'error'
})
})
这是 package.json 中的配置:
"scripts": {
"dev": "vite --host 192.168.31.177",
"build": "vite build",
"preview": "vite preview"
}
然后在 ip 为 192.168.31.45 的机器上启动 expressjs 开发的后端项目 192.168.31.45:3000:
app.get('/api/getNumbers', (req, res) => {
// 生成两个随机数
const number1 = Math.floor(Math.random() * 100);
const number2 = Math.floor(Math.random() * 100);
res.json({
code: 200,
msg: '成功!',
data: {
"a": number1,
"b": number2,
}
});
});
现在想使用 nginx 将前端的请求代理到后端,下面将介绍 nginx 需要怎样配置以及具体原理。
二,配置 nginx
前端项目运行在 192.168.31.177(开发机器),后端运行在 192.168.31.45:3000,Nginx 需要配置为反向代理,将前端请求转发到后端。
在开发机器(192.168.31.177)上 Nginx 的配置文件(nginx.conf):
http {
server {
listen 8001; # Nginx 监听的端口,前端 axios 中配置的 端口
server_name 192.168.31.177; # 前端 axios 中配置的 IP
location / {
try_files $uri $uri/ /index.html; # 支持Vue路由的history模式
}
# 代理后端API请求
location /api {
proxy_pass http://192.168.31.45:3000; # 后端项目运行的地址
# 可选:如果后端接口路径不包含/api,移除前缀
# rewrite ^/api/(.*) /$1 break;
# 添加必要的代理头信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
配置完成后执行:
G:\nginx-1.24.0>nginx -t # 检查配置语法
nginx: the configuration file G:\nginx-1.24.0/conf/nginx.conf syntax is ok
nginx: configuration file G:\nginx-1.24.0/conf/nginx.conf test is successful
G:\nginx-1.24.0>start nginx # 启动nginx
G:\nginx-1.24.0>nginx -s reload # 不停止,重新加载
- 打开【任务管理器——进程,搜索 nginx,可以看到两个进程,说明 nginx 正确启动。
启动前端项目,访问 http://192.168.31.177:5173/。打开页面后调用接口,获取到接口数据。
三,Nginx 代理原理
反向代理的作用:
请求转发:Nginx 监听前端请求(如 http://192.168.31.177:8080/api/getNumbers),并将匹配 /api 的请求转发到后端服务器 http://192.163.109.134:3000。
隐藏后端细节:前端无需知道后端地址,只需与 Nginx 通信。
解决跨域:浏览器认为请求是同源的(都是 http://192.168.31.177:8080),实际由 Nginx 转发到不同域的后端。
关键配置解释
location /api:匹配所有以 /api 开头的请求路径。 proxy_pass:将匹配的请求转发到后端服务器。 proxy_set_header:设置请求头,确保后端能获取客户端的真实 IP 和协议信息。 add_header:添加 CORS 响应头,显式允许跨域(可选,如果代理已解决跨域,可能不需要)。
为什么这样配置?
解决跨域问题:浏览器默认禁止跨域请求,但通过 Nginx 代理:前端请求发送到 http://192.168.31.177:8080/api(同源)。Nginx 将请求转发到 http://192.163.109.134:3000/api,后端响应通过 Nginx 返回前端。浏览器认为请求是“同源”的,不会触发跨域限制。
灵活的路由控制:可以按路径(如 /api)或域名分发请求。
支持负载均衡、缓存等高级功能(开发阶段可能不需要)。
统一入口:前端和后端通过同一个端口(如 8080)通信,简化开发配置。
验证配置是否生效:
- 在浏览器中访问后端 API http://192.163.109.134:3000/api/getNumbers,确保后端正常返回数据。
- 通过 Nginx 访问 API http://192.168.31.177:8080/api/getNumbers,检查是否返回相同数据。
- 检查看 Nginx 的访问日志和错误日志,确认请求是否被正确转发。
- Nginx 未启动或配置错误问题排查
status nginx 检查服务状态。 nginx -t 检查配置语法。