zoukankan      html  css  js  c++  java
  • h5请求跨域问题Access-Control-Allow-Origin解决跨域

    访问后端接口报错:No 'Access-Control-Allow-Origin' header is present on the requested resource

    解决:

    Access-Control-Allow-Origin是HTML5中定义的一种解决资源跨域的策略。

    他是通过服务器端返回带有Access-Control-Allow-Origin标识的Response header,用来解决资源的跨域权限问题。

    在Response header添加Access-Control-Allow-Origin:* 就可以;

    1.例如nginx配置响应头添加Access-Control-Allow-Origin

                    set $origin '*';
                    if ($request_method = 'OPTIONS') {
                        add_header 'Access-Control-Allow-Origin' $origin;
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Max-Age' 1728000;
                        add_header 'Content-Type' 'text/plain charset=UTF-8';
                        add_header 'Content-Length' 0;
                        return 204;
                    }
    
                    if ($request_method = 'POST') {
                        add_header 'Access-Control-Allow-Origin' $origin;
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
                    }
    
                    if ($request_method = 'GET') {
                        add_header 'Access-Control-Allow-Origin' $origin;
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
                    }

     如果发现还是被跨域限制,注意要添加个always,比如使用post请求;nginx已经配置允许跨域信息了,其它就不要配置了,不然会冲突报错;

    在response添加 Access-Control-Allow-Origin,例如

    Access-Control-Allow-Origin:www.google.com

    www.google.com 是访问的域名,根据实际情况设置。

    也可以设置为 * 表示该资源谁都可以用

    Access-Control-Allow-Origin: *

    如果资源是html页面,可以设置 

    <meta http-equiv="Access-Control-Allow-Origin" content="*">

    2php允许ajax跨域访问Access-Control-Allow-Origin,在php顶部添加响应头

     

  • 相关阅读:
    【BZOJ4520】[Cqoi2016]K远点对 kd-tree+堆
    【BZOJ2843】极地旅行社 离线+树链剖分+树状数组
    【BZOJ3251】树上三角形 暴力
    SQL学习笔记三(补充-3)之MySQL完整性约束
    SQL学习笔记三(补充-2)之MySQL数据类型
    SQL学习笔记三(补充-1)之MySQL存储引擎
    SQL学习笔记二之MySQL的数据库操作
    SQL学习笔记一之初识数据库
    深入理解Python中的元类(metaclass)
    Web安全之BurpSuite抓取HTTPS请求
  • 原文地址:https://www.cnblogs.com/JahanGu/p/10180242.html
Copyright © 2011-2022 走看看