2017-07-29 62 views
0

我試圖調用一個陣營應用Twitter的API,並出現以下錯誤我可以使用Fetch在客戶端調用Twitter API嗎?

提取API無法加載 https://api.twitter.com/1.1/account/verify_credentials.json。對預檢請求的響應 未通過訪問控制檢查:否 「所請求的 資源上存在」Access-Control-Allow-Origin「標頭。原因'http://localhost:3000'因此不允許 訪問。響應的HTTP狀態碼爲400.如果一個不透明的響應 滿足您的需求,請將請求的模式設置爲'no-cors'以取消禁用CORS的 資源。

我知道Access-Control-Allow-Origin是什麼意思。我認爲我遵循Twitter API的所有步驟(Authorizing a request,Creating a signature),但也許我忽略了我的代碼中的某些內容。

另外我沒有在API文檔中發現任何說我必須使用服務器來調用他們的API,但也許我錯過了什麼。

以下是獲取用戶信息的函數文字fetchUser

export const fetchUser = async() => { 
    const oauths = {...OAUTHS, oauth_nonce: generateNonce(), oauth_timestamp: Math.floor(Date.now()/1000)}; 
    const oauthKeys = Object.keys(oauths); 
    const oauthValues = Object.values(oauths); 
    const baseUrl = `${ROOT_API_URL}verify_credentials.json`; 
    const signature = generateOauthSignature(
    oauths, 
    HTTP_GET, 
    baseUrl, 
    CONSUMER_SECRET, 
    OAUTH_SECRET 
); 

    const response = await fetch(baseUrl, { 
    method: `${HTTP_GET}`, 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Authorization': `OAuth ${oauthKeys[0]}="${oauthValues[0]}",${oauthKeys[1]}="${oauthValues[1]}",oauth_signature="${signature}",${oauthKeys[2]}="${oauthValues[2]}",${oauthKeys[3]}="${oauthValues[3]}",${oauthKeys[4]}="${oauthValues[4]}",${oauthKeys[5]}="${oauthValues[5]}"`, 
    } 
    }); 
    const body = await response.json(); 

    if (response.status !== 200) 
    throw Error(body.message); 

    return body; 
} 

Take a look at the entire code I am using (CodePen)

+0

我敢肯定,你需要一臺服務器,因爲有一個在文檔沒有CORS頭......有各種各樣的第三方工具/從客戶端JS使用twitter API的「webify」方面的服務。 – dandavis

+0

感謝您的信息,你知道一個好的工具嗎?我做了一個快速的谷歌搜索,但似乎無法找到任何東西 – esausilva

+0

作爲一個很好的工具,可以嘗試設置https://github.com/Rob--W/cors-anywhere/等實例,並查看如果你能以你需要的方式解決問題。有關更多詳細信息,請參閱https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource/42744707#42744707 – sideshowbarker

回答

0

我不得不創建一個節點服務器調用API,根本不算什麼

0

我不知道用是否Twitter的API允許CORS,但如果這樣做,在你的請求指定CORS模式應該做的伎倆

const response = await fetch(baseUrl, { 
    method: `${HTTP_GET}`, 
    mode: 'cors', 
    headers: { 
    'Content-Type': 'application/x-www-form-urlencoded', 
    'Authorization': `OAuth ${oauthKeys[0]}="${oauthValues[0]}",${oauthKeys[1]}="${oauthValues[1]}",oauth_signature="${signature}",${oauthKeys[2]}="${oauthValues[2]}",${oauthKeys[3]}="${oauthValues[3]}",${oauthKeys[4]}="${oauthValues[4]}",${oauthKeys[5]}="${oauthValues[5]}"`, 
} 

});

+0

它似乎不允許CORS – esausilva

相關問題