一,项目配置
我在 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 检查配置语法。
复制代码 四,源码
nginx代理前端哀求——教程源码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|