我试图在React App中调用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的所有步骤(授权请求,创建签名),但是也许我忽略了代码中的某些内容。
Access-Control-Allow-Origin
另外,我在API文档中找不到任何内容,说我必须使用服务器来调用其API,但也许我错过了一些东西。
下面是fetchUser获取用户信息的函数文字。
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; }
看看我正在使用的整个代码(CodePen)
我必须创建一个Node服务器来调用API,没什么大不了的