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顶部添加响应头

     

  • 相关阅读:
    创建类以及引用一个类
    修改hosts文件
    微信第三方登录接口开发
    Android定位
    Leetcode 102. Binary Tree Level Order Traversal
    Leetcode 725. Split Linked List in Parts
    Leetcode 445. Add Two Numbers II
    Leetcode 328. Odd Even Linked List
    Leetcode 237. Delete Node in a Linked List
    Leetcode 234. Palindrome Linked List
  • 原文地址:https://www.cnblogs.com/JahanGu/p/10180242.html
Copyright © 2011-2022 走看看