2017-08-02 122 views
0

我試圖從我們的TeamCity服務器使用axios get請求將數據返回到我的React web應用程序。不幸的是,我無法在服務器上啓用CORS,並始終以401:未授權,或「預檢無效(重定向)響應」錯誤結束。禁用CORS的TeamCity Rest API調用 - axios獲取請求

我曾嘗試通過用戶名和密碼在標題:

componentDidMount() { 
var config = { 
    "headers": { 
    "username": "username", 
    "password": "password"  
    } 
} 
// Make axios http request to TeamCity server with authentication headers 
axios.get('http://teamcity/app/rest', config) 
.then(res => res.json()) 
    .then(res => { 
    // Transform the raw data by extracting the nested posts 
    const projects = res.data.projects; 

    // Update state to trigger a re-render. 
    // Clear any errors, and turn off the loading indicator. 
    this.setState({ 
     projects, 
     loading: false, 
     error: null 
    }); 
    }) 
    .catch(err => { 
    // Something went wrong. Save the error in state and re-render. 
    this.setState({ 
     loading: false, 
     error: err 
    }); 
    }); 
} 

我曾嘗試通過用戶名和密碼的網址按這個帖子: How to pass username and password in TeamCity REST API

http://user:[email protected]/app/rest/ 

我也嘗試從工作郵遞員請求中傳遞基本身份驗證標頭。

請求總是返回'XMLHttpRequest無法加載http://teamcity/app/rest。預檢反應無效(重定向)'

我與TeamCity服務器位於同一網絡中。這可能沒有啓用CORS?

+0

它似乎是一個身份驗證問題。您沒有按預期傳遞用戶/傳球。 – Akhil

回答

1

您必須啓用CORS。否則(即使TeamCity使用某些數據作出迴應),將無法在瀏覽器中訪問響應。

一旦您向rest.cors.originsinternal property提供了正確的來源,例如,

rest.cors.origins=http://myinternalwebpage.org.com:8080,https://myinternalwebpage.org.com 

你也應該能夠通過添加下列內部屬性預檢OPTIONS請求支持:

rest.cors.optionsRequest.allowUnauthorized=true 

並重新啓動服務器。

The docs也建議使用/app/rest/latest,而不是/app/rest,並避免httpAuth前綴。

之後,一切都應該很好,例如,

fetch('http://teamcity:8111/bs/app/rest/latest/builds?count=1', 
{ 
    headers: { 
    'Authorization': 'Basic '+btoa('user:pass'), 
    'Accept': 'application/json' 
    } 
}) 
.then(r => r.json()) 
.then(r => console.log(r))