1. 程式人生 > >No 'Access-Control-Allow-Origin' header is present之 為什麼會跨域及解決方案

No 'Access-Control-Allow-Origin' header is present之 為什麼會跨域及解決方案

1 瀏覽器的限制

2 跨域

3 瀏覽器傳送的是 XHR (XMLHttpRequest)請求

當以上三個條件都滿足時瀏覽器會丟擲跨域請求異常(記住是瀏覽器丟擲的異常,和服務端沒太大關係),在講跨域請求解決方案前先了解幾個問題。

1 http請求中,哪些是常見的簡單請求,哪些是非簡單請求

常見的簡單請求:請求方法為:GET ,HEAD,POST,請求header裡面無自定義頭,Content-Type為以下幾種:text/plain  multipart/form-data application/x-www-form-urlencoded

常見的非簡單請求 :請求方法為:put delete的ajax請求,傳送json格式的ajax請求,帶自定義頭的ajax請求

2 瀏覽器在傳送跨域請求時候,會有哪些過程

如果是簡單請求,瀏覽器會先發送請求,然後判斷伺服器返的返回頭中是否支援跨域請求,否則丟擲跨域異常

如果是非簡單請求,瀏覽器會先發出OPTIONS請求方法的檢測命令,判斷伺服器是否支援跨域請求,如果支援則傳送真正的請求,如果不支援則丟擲跨域異常,因此一個非簡單請求每次會發送兩個請求,後面跨域解決方案會講到快取OPTIONS預檢請求

跨域解決方案

方案1:  禁用瀏覽器跨域校驗,即允許跨域訪問,(這種方案不可取,不可能讓所有的瀏覽器設定允許跨域訪問)

谷歌瀏覽器禁用跨域校驗: 建立一個快捷方式傳送到桌面 ,快捷方式--》右鍵---》屬性頁面中的目標輸入框里加上  --disable-web-security --user-data-dir=C:\Program Files (x86)\Google\Chrome\Application (注意:--user-data-dir的值就是瀏覽器安裝目錄。)

方案2: 採用jsonp方式,需要後臺和前臺同時改動程式碼,

1 前臺需要設定callback引數,如果使用的是jquery ajax 那麼dateType屬性設定為jsonp,jquery框架會自動設定引數名為callback的請求引數,也可以通過jsonp屬性修改jsonp請求引數名,其他js框架根據具體api使用,

2 後臺接收到callback引數後認為是jsonp請求,需要返回jsonp格式,普通json請求返回的content-Type是application/json,而jsonp返回的是application/javascript,同時也證明了jsonp請求服務端返回的是js指令碼

3 jsonp請求引數名前後約定需要相同,例如jquery預設使用的是callback

弊端:jsonp 需要前後端都去修改程式碼,且jsonp是通過動態建立script指令碼傳送請求,僅支援 GET方法,jsonp發出的請求不是xhr請求,也是能解決跨域的原因

方案3 服務端解決跨域問題

通過編寫filter在response物件中新增響應頭,告訴瀏覽器允許跨域訪問,* 號程式碼允許所有的請求域名,所有的請求方法跨域訪問

//告訴瀏覽器允許所有的域訪問
//注意 * 不能滿足帶有cookie的訪問,Origin 必須是全匹配
//resp.addHeader("Access-Control-Allow-Origin", "*");
//解決辦法通過獲取Origin請求頭來動態設定
String origin = request.getHeader("Origin");
if (StringUtils.hasText(origin)) {
    resp.addHeader("Access-Control-Allow-Origin", origin);
}
//允許帶有cookie訪問
resp.addHeader("Access-Control-Allow-Credentials", "true");
//告訴瀏覽器允許跨域訪問的方法
resp.addHeader("Access-Control-Allow-Methods", "*");
//告訴瀏覽器允許帶有Content-Type,header1,header2頭的請求訪問
//resp.addHeader("Access-Control-Allow-Headers", "Content-Type,header1,header2");
//設定支援所有的自定義請求頭
String headers = request.getHeader("Access-Control-Request-Headers");
if (StringUtils.hasText(headers)){
    resp.addHeader("Access-Control-Allow-Headers", headers);
}
//告訴瀏覽器快取OPTIONS預檢請求1小時,避免非簡單請求每次傳送預檢請求,提升效能
resp.addHeader("Access-Control-Max-Age", "3600");

方案4 Spring框架提供了跨域解決方案

spring提供了 @CrossOrigin註解使用者解決跨域問題,同時支援全域性配置
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/api/**")
			.allowedOrigins("http://domain2.com")
			.allowedMethods("PUT", "DELETE")
			.allowedHeaders("header1", "header2", "header3")
			.exposedHeaders("header1", "header2")
			.allowCredentials(false).maxAge(3600);
	}
}

方案5 服務端通過ngnix解決跨域問題 

location /{
            proxy_pass http://localhost:8080/;
           
            #告訴瀏覽器允許跨域訪問的方法
            add_header Access-Control-Allow-Methods *;
            # 告訴瀏覽器快取OPTIONS預檢請求1小時
            add_header Access-Control-Max-Age 3600;
            #允許帶有cookie訪問
            add_header Access-Control-Allow-Credentials true;
            #注意 * 不能滿足帶有cookie的訪問,Origin 必須是全匹配,這裡通過變數獲取
            add_header Access-Control-Allow-Origin $http_origin;
            #設定支援所有的自定義請求頭
            add_header Access-Control-Allow-Headers $http_access_control_request_headers;
            #如果預檢請求,則返回成功,不需要轉發到後端
            if ($request_method = OPTIONS){
                return 200;
            }
        }

方案6 客戶端通過nginx隱藏跨域

#轉發全部以/api開頭的請求到web伺服器
   location  /api
   {
        proxy_pass http://127.0.0.1:8080/api;
   }

相關推薦

No 'Access-Control-Allow-Origin' header is present 為什麼解決方案

1 瀏覽器的限制 2 跨域 3 瀏覽器傳送的是 XHR (XMLHttpRequest)請求 當以上三個條件都滿足時瀏覽器會丟擲跨域請求異常(記住是瀏覽器丟擲的異常,和服務端沒太大關係),在講跨域請求解決方案前先了解幾個問題。 1 http請求中,哪些是常見的簡單請求

js訪問,NoAccess-Control-Allow-Originheader is present on

在本地用ajax跨域訪問請求時報錯:   XMLHttpRequest cannot loadhttp://www.zjblogs.com/. No 'Access-Control-Allow-Origin' header is present on the requested r

解決Vue請求 ‘No 'Access-Control-Allow-Origin' header is present on the requested resource’錯誤

如果我們用VueResouce直接請求,這樣寫(以豆瓣api為例): this.$http.get('https://api.douban.com//v2/movie/top250').then((response) => { this.movie =

No 'Access-Control-Allow-Origin' header is present on the requested resource.'Ajax訪問解決方案

出現該錯誤是由於存在網站跨域訪問的問題。 什麼是網站跨域,簡單來講,當你通過ajax來請求或傳送資料時,兩個域名之間不能跨過域名來發送請求或者請求資料,瀏覽器會認為它是不安全的。 解決方式: 1、伺服器端解決方案 設定響應報文頭 response.setHeader

Cesium載入傾斜攝影模型,cors的問題No 'Access-Control-Allow-Origin' header is present on the requested resource

    用Cesium載入傾斜攝影模型時,會存在cors跨域的問題,報No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:

NoAccess-Control-Allow-Originheader is present on the requested resource 報錯原因解決方案

跨域——Cross-Origin Resource Sharing 跨域請求:簡單說,不同域名之間可以請求到資料的行為; 報錯資訊: Failed to load https://example.com/: No ‘Access-Control-Allow-O

VUE開發報錯No 'Access-Control-Allow-Origin' header is present on the requested resource.

近來被領導安排去做前端幫忙,使用的是VUE+elementUI。今天完成修改密碼功能時,出現如下問題:Failed to load http://xxxxxxxxx/motifyUserPwd: No 'Access-Control-Allow-Origin' header

jFinal解決問題 No 'Access-Control-Allow-Origin' header is present on the requested resource

前端ajax請求後端java實現跨域問題,看了很多方法說前端這是jsonp什麼的並沒有解決, $.ajax({ type:"post", url:"http://sdfgadsgfasdg

arcgis js api呼叫SOE 設定代理後 呼叫報No 'Access-Control-Allow-Origin' header is present on the requested ...

使用ArcGIS API for JavaScript 呼叫SOE,在設定了代理之後進行請求 報“No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'nul

本地Ajax訪問 No 'Access-Control-Allow-Origin' header is present on the requested resource.

XMLHttpRequest cannot load http://lefeier.net/storemessage.php. No ‘Access-Control-Allow-Origin’ header is present on the request

No 'Access-Control-Allow-Origin' header is present on the requested resource', 訪問的解決方法

1. 當請求不在同一域名下的資原始檔(ip地址+埠號)時,會報如下錯誤: “No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://

Post request is No 'Access-Control-Allow-Origin' header is present on the requested resource問題解決

跨域問題 報錯資訊為:post request is No ‘Access-Control-Allow-Origin’ header is present on the requested resou

Vue報錯筆記(2):No 'Access-Control-Allow-Origin' header is present on the requested resource.

就是說:當使用ajax訪問遠端伺服器時,請求失敗,瀏覽器報如上錯誤。這是出於安全的考慮,預設禁止跨域訪問導致的 1. 什麼時跨域訪問 舉個栗子:在A網站中,我們希望使用Ajax來獲得B網站中的特定內容。如果A網站與B網站不在同一個域中,那麼就出現了跨域

ajax請求:No 'Access-Control-Allow-Origin' header is present on the requested resource

ajax跨域請求報錯解決辦法<script type="text/javascript"> $(document).ready(function () { $.ajax({ type : "POST", url : "h

Ajax請求問題,報錯XMLHttpRequest cannot load ''. No 'Access-Control-Allow-Origin' header is present on t

報錯:XMLHttpRequest cannot load  ''. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ' is therefore 

ajax(No 'Access-Control-Allow-Origin' header is present on the requested resource)

一、跨域問題: eg:在A網站中,我們希望使用Ajax來獲得B網站中的特定內容。如果A網站與B網站不在同一個域中,那麼就出現了跨域訪問問題。你可以理解為兩個域名之間不能跨過域名來發送請求或者請求資料,否則就是不安全的。跨域訪問違反了同源策略。 總而言之,同源策略規定,瀏覽器

解決No 'Access-Control-Allow-Origin' header is present on the requested resource”

1. 問題描述 在js中使用ajax請求在網頁控制檯下列印以下錯誤資訊: XMLHttpRequest cannot load http://192.168.2.46:8000/account/getjson/. No 'Access-Control-All

No 'Access-Control-Allow-Origin' header is present 為什麼解決方案

1 瀏覽器的限制 2 跨域 3 瀏覽器傳送的是 XHR (XMLHttpRequest)請求 當以上三個條件都滿足時瀏覽器會丟擲跨域請求異常(記住是瀏覽器丟擲的異常,和服務端沒太大關係),在講跨域請求解決方案前先了解幾個問題。 1 http請求中,哪些是常見的簡單請求,哪些是非簡單請

Spring Cloud (6) | spring cloud zuul 問題No 'Access-Control-Allow-Origin' header

在用spring cloud zuul做Filter的時候,訪問微服務出現跨域問題,在網上找了很多辦法: zuul: ignored-headers: Access-Control-Allow

[Access-Control-Allow-Origin]Web中使用filter實現訪問問題

web.xml配置過濾器 在web.xml中定義一個isCross初始化變數,用於開啟是否允許跨域訪問。這將很好的控制跨域訪問問題。 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-