skip to Main Content

I am trying to call the Twitter API in a React App and get the following error

Fetch API cannot load
https://api.twitter.com/1.1/account/verify_credentials.json. 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:3000‘ is therefore not allowed
access. The response had HTTP status code 400. If an opaque response
serves your needs, set the request’s mode to ‘no-cors’ to fetch the
resource with CORS disabled.

I know what Access-Control-Allow-Origin means. I think I followed all the steps per the Twitter API (Authorizing a request, Creating a signature) but maybe I am overlooking something in my code.

Also I did not find anything in the API docs that say I have to use a server to call their API, but maybe I missed something.

Below is the function literal fetchUser that gets the user information.

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)

2

Answers


  1. Chosen as BEST ANSWER

    I had to create a Node server to call the API, no biggie


  2. I do not know wether or not the Twitter API allows CORS, but if it does, specifying cors mode in your request should do the trick

    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]}"`,
    }
    

    });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search