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

     

  • 相关阅读:
    子序列自动机
    poj 暴力水题
    小白贪心题
    组合数+费马大/小定理
    随机数法
    vector的二维用法+前缀和
    巨思维题
    思维水题
    Codeforces Round #323 (Div. 2) D.Once Again... (nlogn LIS)
    Codeforces Round #325 (Div. 2) D. Phillip and Trains (BFS)
  • 原文地址:https://www.cnblogs.com/JahanGu/p/10180242.html
Copyright © 2011-2022 走看看