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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

昆明--菜鸟入门   2021-01-14 我要评论
这篇文章主要给大家介绍了关于Nginx解决前端访问资源跨域问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

被前端跨域问题折磨快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',就会出现

那么我们进行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)
   },
})

结果:(访问成功)

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们