系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > server > anz > 详细页面

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

时间:2021-01-13来源:www.pcxitongcheng.com作者:电脑系统城

被前端跨域问题折磨快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/

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

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

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

那么我们进行Nignx配置

编辑 /config/nginx.conf此文件

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

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

2)设置反向代理

1
2
3
4
5
6
7
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为地址开头

才会进行地址转发

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

结果:(访问成功)

总结

到此这篇关于Nginx解决前端访问资源跨域问题的文章就介绍到这了,更多相关Nginx解决前端访问资源跨域内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载