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

     

  • 相关阅读:
    redis基本命令1
    MySQL笔记01(黑马)
    尚硅谷Java——宋红康笔记【day25-day29】
    尚硅谷Java——宋红康笔记【day19-day24】
    Java网络编程实践
    框架高频面试题
    多线程面试题
    尚硅谷Java——宋红康笔记【day11-day18】
    尚硅谷Java——宋红康笔记【day6-day10】
    尚硅谷Java——宋红康笔记【day1-day5】
  • 原文地址:https://www.cnblogs.com/JahanGu/p/10180242.html
Copyright © 2020-2023  润新知