Nginx解决前端访问资源跨域问题的方法详解

来自:互联网
时间:2021-01-11
阅读:

被前端跨域问题折磨快2天后,终于用ngnx的方式解决了,所以在此总结下。

该篇只探讨如何用Ngnx解决跨域问题,对于原理不作讨论。

1、首先介绍Windows环境下Nignx的相关命令操作

nginx常用命令:

验证配置是否正确: nginx -t 查看Nginx的版本号:nginx -V 启动Nginx:start nginx 快速停止或关闭Nginx:nginx -s stop 正常停止或关闭Nginx:nginx -s quit 配置文件修改重装载命令:nginx -s reload

在停止ngix后,会自动删除/logs目录下的nginx.pid

可以使用命令nginx -c conf/nginx.conf 重新创建 或者 再次启动nginx

查看nignx 监听端口 是否启动成功

netstat -ano | findstr 端口号

解决关闭nignx后 端口仍在监听中

1、netstat -ano | findstr 端口号 #获取到PID

2、tasklist | findstr "PID" #命令找到nginx进程信息

3、taskkill /f /t /im nginx.exe #结束nginx进程

2、介绍如何配置Nignx 解决跨域问题

前端ip端口号:http://localhost:8080/

后端ip端口号:http://localhost:8082/

现在我们在不做跨域设置时,前端请求如下

uni.request({
  url:'http://localhost:8082/ApiController/test',
  success:(res)=>{
  console.log(res.data)
  },
})

访问地址:'http://localhost:8082/ApiController/test',就会出现

Nginx解决前端访问资源跨域问题的方法详解

那么我们进行Nignx配置

编辑 /config/nginx.conf此文件

1)添加头信息,在nginx.conf配置文件http块中添加跨域访问配置

add_header Access-Control-Allow-Origin *; //允许所有域名跨域访问代理地址
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET; //跨域请求访问请求方式,

2)设置反向代理

server {
  listen  80; #配置nignx的监听端口
  server_name localhost; #配置nignx的监听地址
  location /ApiController{ #监听地址 以/ApiController开头的地址
   proxy_pass http://localhost:8082; #转发地址
  }
}

此时配置后我们前端访问url

http://localhost:8082/ApiController/test 应修改为http://localhost:80/ApiController/test

#此时监听

以localhost为域名

以80为端口

以/ApiController为地址开头

才会进行地址转发

uni.request({
   url:'http://localhost:80/ApiController/test',
   success:(res)=>{
   console.log(res.data)
   },
})

结果:(访问成功)

Nginx解决前端访问资源跨域问题的方法详解

返回顶部
顶部