2017-06-14 19 views
1

我試圖使用提取創建獲取請求。請求看起來像這樣:使用僅提取選項創建獲取請求發送

fetch('https://requestb.in/14ikb6j1', { 
    method: 'get', 
    headers: { 
    'Authorization': 'Token token=xxxxx' 
    }}); 

如果我向我自己的服務器發出這個請求,它每次都會在選項請求上失敗。我無法弄清楚爲什麼。

如果我向requestbin發出這個請求,首先有一個選項請求。但是,在收到選項響應之後,實際的獲取請求將不會生成。

這是requestbin收到什麼:

OPTIONS /14ikb6j1 

HEADERS 

Referer: http://localhost:9000/ 
Host: requestb.in 
Total-Route-Time: 0 
Via: 1.1 vegur 
Accept-Encoding: gzip 
Cf-Visitor: {"scheme":"https"} 
Cf-Ipcountry: NL 
Cf-Ray: 36edd35d1cad2b28-AMS 
Cf-Connecting-Ip: 37.153.231.90 
Connection: close 
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 
Accept: */* 
Connect-Time: 1 
Access-Control-Request-Method: GET 
Content-Length: 0 
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4 
X-Request-Id: 69b120c1-0f18-454b-a7fd-91f082252a06 
Access-Control-Request-Headers: authorization 
Origin: http://localhost:9000 

這就是鉻日誌:

chrome dev tools


最奇怪的是,我得到一個200 - OK地位的結果。控制檯但是,仍然記錄此:

Fetch API cannot load https://requestb.in/14ikb6j1 . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:9000 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. :9000/#/branching:1 Uncaught (in promise) TypeError: Failed to fetch

但是,如果我讓郵差用它工作這個請求:postman request

GET /14ikb6j1 
HEADERS 

Cf-Ipcountry: NL 
Cf-Ray: 36eddb797ebf7223-AMS 
Authorization: Token token=xxxx 
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 
Total-Route-Time: 0 
Via: 1.1 vegur 
Connection: close 
Cf-Connecting-Ip: 37.153.231.90 
Connect-Time: 0 
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4 
Postman-Token: 57486701-6f9a-4aab-be1b-776f0d376920 
Accept: */* 
Host: requestb.in 
X-Request-Id: 73a7a35e-0d89-41fd-b760-2aa952349871 
Accept-Encoding: gzip 
Cf-Visitor: {"scheme":"https"} 
Cache-Control: no-cache 

我怎樣才能讓這個獲得與認證頭的請求工作?

+0

''Content-Type':'application/json'' for a GET request。是對的嗎? – Forivin

+0

@Forivin對不起,您是對的。更新後,刪除這些內容類型標題不會改變任何內容。 – Randy

回答

2

這可能是一個CORS問題。您將請求關閉的服務器不允許來自不同域的請求。 檢查您的瀏覽器控制檯並查找錯誤。你可能會發現像這樣的東西:

Fetch API cannot load https://requestb.in/14ikb6j1 . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' https://localhost:9000 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

+0

但是,爲什麼我的郵遞員申請工作,如果Cors被禁用? – Randy

+1

因爲郵遞員沒有域名。它就像是打開網站的普通用戶一樣。當瀏覽器擴展郵遞員獲得這些特權時,該網站無法自行獲取。這是瀏覽器內置的一項簡單的安全功能,用於防止網站A與網站B進行通信,除非網站B對其有好處。 – Forivin