用户登录
用户注册

分享至

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

  • 作者: 请叫我贵阳段王爷
  • 来源: 51数据库
  • 2021-08-25

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

结果:(访问成功)

总结

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

软件
前端设计
程序设计
Java相关