目 录CONTENT

文章目录

Nginx配置跨域

在水一方
2022-10-24 / 0 评论 / 0 点赞 / 551 阅读 / 1,804 字 / 正在检测是否收录...

前言

本文为转载文章,基于实际中遇到的一个两个前端项目之间的访问场景,由于之前一直都是在后端项目中直接配置了跨域,本次的需求并没有涉及到前端调用后端的接口,参考并解决了,于是记录一下

什么是跨域请求

跨域请求就是指:当前发起请求的域与该请求指向的资源所在的域不一样。这里的域指的是这样的一个概念:我们认为若协议 + 域名 + 端口号均相同,那么就是同域。

举个例子:假如一个域名为aaa.cn的网站,它发起一个资源路径为aaa.cn/books/getBookInfo的 Ajax 请求,那么这个请求是同域的,因为资源路径的协议、域名以及端口号与当前域一致(例子中协议名默认为http,端口号默认为80)。但是,如果发起一个资源路径为bbb.com/pay/purchase的 Ajax 请求,那么这个请求就是跨域请求,因为域不一致,与此同时由于安全问题,这种请求会受到同源策略限制。

常见跨域情况

网络协议不同,如http协议访问https协议 ;
端口不同,如80端口访问8080端口 ;
域名不同,如www.test1.com访问www.test2.com ;
子域名不同,如abc.test1.com访问def.test1.com ;
3 nginx跨域示例演示
准备一个nginx服务器,配置为

server {
listen 80; # 监听的端⼝
server_name www.zwx.com; # 域名或ip
location / { # 访问路径配置
root /usr/share/nginx/html;# 根⽬录
index index.html index.htm; # 默认⾸⻚
}
error_page 500 502 503 504 /50x.html; # 错误⻚⾯
location = /50x.html {
root html;
}
}

在html目录里有一个wel.html文件

nginx-cors-test
nginx跨域请求测试
然后启动一个springboot应用,或者tomcat也可以,访问一个html页面

wel1.html

nginx-cors-test

然后访问localhost:9000/wel1.html

点击测试按钮

出现了跨域访问错误

4 修改nginx server 配置
添加如下内容


server {
      listen 80; # 监听的端⼝
       server_name localhost; # 域名或ip
      location / { # 访问路径配置
  #允许跨域请求的域,* 代表所有
      add_header 'Access-Control-Allow-Origin' *;
      #允许带上cookie请求
      add_header 'Access-Control-Allow-Credentials' 'true';
      #允许请求的方法,比如 GET/POST/PUT/DELETE
      add_header 'Access-Control-Allow-Methods' *;
      #允许请求的header
      add_header 'Access-Control-Allow-Headers' *;
      root /usr/share/nginx/html;# 根⽬录
      index index.html index.htm; # 默认⾸⻚
      }
      error_page 500 502 503 504 /50x.html; # 错误⻚⾯
      location = /50x.html {
      root html;
      }
}

然后重启nginx再次测试

跨域求成功了
最重要的就是要在被跨域的nginx配置添加如下配置

      #允许跨域请求的域,* 代表所有
      add_header 'Access-Control-Allow-Origin' *;
      #允许带上cookie请求
      add_header 'Access-Control-Allow-Credentials' 'true';
      #允许请求的方法,比如 GET/POST/PUT/DELETE
      add_header 'Access-Control-Allow-Methods' *;
      #允许请求的header
      add_header 'Access-Control-Allow-Headers' *;


转自:
https://blog.csdn.net/weixin_44273388/article/details/124206129

0

评论区