app开发定制公司Nginx配置跨域(CORS)

1 app开发定制公司什么是跨域请求

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

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

2.常见跨域情况

  • 网络协议不同,如http协议访问https协议 ;
  • 端口不同,如80端口访问8080端口 ;
  • 域名不同,如www.test1.com访问www.test2.com ;
  • 子域名不同,如abc.test1.com访问def.test1.com ;

3 跨域示例演示

准备一个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文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>nginx-cors-test</title>
  6. </head>
  7. <body>
  8. <div>nginx跨域请求测试</div>
  9. </body>
  10. </html>

然后启动一个springboot应用,或者tomcat也可以,访问一个html页面

wel1.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>nginx-cors-test</title>
  6. </head>
  7. <body>
  8. <button type="button" onclick="test()">nginx跨域请求测试</button>
  9. <div id="test"></div>
  10. </body>
  11. <script src="jquery-1.10.2.min.js"></script>
  12. <script>
  13. function test() {
  14. $.get("http://192.168.75.128/wel.html",null,function(result) {
  15. alert("跨域请求成功");
  16. });
  17. }
  18. </script>
  19. </html>

然后访问localhost:9000/wel1.html

点击测试按钮

出现了跨域访问错误

4 修改nginx server 配置

添加如下内容

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

然后重启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' *;

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发