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頂部添加響應頭

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM