2016-03-15 59 views
1

找不到任何文檔,因此在深入研究代碼之前,沒有人知道如何在使用'fetch'發出REST請求時使用基本身份驗證(https://github.com/github/fetch) 。帶有提取的基本身份驗證(或任何身份驗證)

剛試過以下行,但頭部沒有在請求中設置:

fetch('http://localhost:8080/timeEntry', { 
     mode: 'no-cors', 
     headers: { 'Authorization': 'Basic YW5kcmVhczpzZWxlbndhbGw=' } 
    }) 
    .then(checkStatus) 
    .then(parseJSON) 
    .then(function(activities) { 
     console.log('request succeeded with JSON response', data); 
     dispatch(activitiesFetched(activities, null)); 
    }).catch(function(error) { 
     console.log('request failed', error); 
     dispatch(activitiesFetched(null, error)); 
    }); 

的用戶名和密碼是我自己的姓和名,用curl它的工作原理。

如果我把{ 'Accept' : 'application/test' }接受設置,只是不是Authorization ...奇怪。

只是爲了能夠繼續,我添加了credentials: 'include',它使瀏覽器提示輸入用於與REST後端進行通信的用戶名和密碼。只是爲了測試,將進一步使用OAuth。

fetch('http://localhost:8080/timeEntry', { 
     mode: 'no-cors', 
     credentials: 'include' 
    }) 
    .then(checkStatus) 
    .then(parseJSON) 
    .then(function(activities) { 
     console.log('request succeeded with JSON response', data); 
     dispatch(activitiesFetched(activities, null)); 
    }).catch(function(error) { 
     console.log('request failed', error); 
     dispatch(activitiesFetched(null, error)); 
    }); 
+0

「認證」是什麼意思?你想要做什麼? – Pointy

+0

我使用Spring Boot來公開REST api,並且它需要基本身份驗證,因爲我現在已經設置了它。基本上我想做一個「授權:基本QWxhZGRpbjpPcGVuU2VzYW1l」...但在發送標題之前,我只想檢查功能是否構建到獲取api中。 –

+1

據我所知,基本身份驗證只是設置標題,所以它應該很簡單,只需將一些添加到傳遞給函數的對象即可。 – JCOC611

回答

0

因爲它看起來像你正在使用的庫是一個Fetch API填充工具,我要離開假設語法應通過攜帶爲好工作。

我Mozilla的網頁上找到的樣本表明,fetch方法簽名fetch('API_ENDPOINT', OBJECT)其中object樣子:

myHeaders = new Headers({ 
    "Authorization": "Basic YW5kcmVhczpzZWxlbndhbGw=" 
}); 

var obj = { 
    method: 'GET', 
    headers: myHeaders 
}) 

因此該方法變爲:

fetch('http://localhost:8080/timeEntry', obj) 
    .then(checkStatus) 
    .then(parseJSON)... 

我還沒有測試此代碼,但它似乎與我所能找到的一致。希望這可以指導你正確的方向。