栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > 服务器

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

服务器 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

被前端跨域问题折磨快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解决前端访问资源跨域内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/176488.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号