question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

400 CORS Error when using library from the client

See original GitHub issue

Maybe this is something on my end, but I am following the documentation and I have this code

import Twitter from 'twitter-lite'

const client = new Twitter({
  subdomain: "api",
  consumer_key: process.env.CONSUMER_KEY, // from Twitter.
  consumer_secret: process.env.CONSUMER_SECRET, // from Twitter.
  access_token_key: process.env.ACCESS_TOKEN_KEY, // from your User (oauth_token)
  access_token_secret: process.env.ACCESS_TOKEN_SECRET // from your User (oauth_token_secret)
});

client
  .get("statuses/user_timeline.json?screen_name=twitterapi&count=2")
  .then(results => {
    console.log("results", results);
  })
  .catch(console.error);

but I am getting this response when running my code

Failed to load resource: the server responded with a status of 400 ()

Access to XMLHttpRequest at 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2.json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

TypeError: Network request failed at XMLHttpRequest.xhr.onerror

However, I am able to successfully hit this end point with the same tokens in Postman. Any ideas! Hoping to get this working soon, thanks!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:11

github_iconTop GitHub Comments

1reaction
DancePartycommented, Jan 18, 2019

Okay, didn’t know if it was on my end. I can possibly look into contributing some tests this weekend!

0reactions
acaillycommented, Jan 15, 2021

I think I found the origin of the 401 error.

This lib delegate authentication header generation to oauth-1.0a dependency (https://github.com/ddo/oauth-1.0a) when it uses Twitter OAuth 1.0a authentication method (https://developer.twitter.com/en/docs/authentication/oauth-1-0a)

Authentication header should be computed with the endpoint URL without the proxy, but when you pass the subdomain containing the CORS proxy, it is used everywhere, event for this authentication header generation.

I found this workaround:

  // In browser, use a CORS proxy
  // From https://github.com/draftbit/twitter-lite/issues/41#issuecomment-467403918
  const subdomain = isBrowser
    ? `${configuration.corsProxyURL.slice("https://".length)}https://api`
    : "api";

  const client = new Twitter({
    subdomain,
    version: "1.1",
    consumer_key: consumerKey,
    consumer_secret: consumerSecret,
    access_token_key: accessTokenKey,
    access_token_secret: accessTokenSecret,
  });

  // Monkey patch oauth client used by twitter-lite in order to
  // ignore cors proxy url when generating authentication headers
  const originalAuthorizeFunction = client.client.authorize;
  client.client.authorize = function (request, token) {
    let requestWihoutCorsProxy = request;
    if (request.url.startsWith(configuration.corsProxyURL)) {
      const requestUrlNotProxyfied = request.url.slice(
        configuration.corsProxyURL.length
      );
      requestWihoutCorsProxy = { ...request, url: requestUrlNotProxyfied };
    }
    return originalAuthorizeFunction.call(
      client.client,
      requestWihoutCorsProxy,
      token
    );
  };
Read more comments on GitHub >

github_iconTop Results From Across the Web

What Is a CORS Error and How to Fix It (3 Ways) - Bannerbear
A CORS error is common when making an HTTP request to another origin. You can get rid of it using one of the...
Read more >
Stripe integrations fetch return cors error 400 - Stack Overflow
Stripe docs says the request was unacceptable - 400 bad request is often due to missing a required parameter, so check the API...
Read more >
Getting a cors error 400 bad request and I have my ... - Reddit
It looks like you're sending invalid JSON and the backend is returning a 400, which is not a valid CORS response. Send valid...
Read more >
CORS errors - HTTP - MDN Web Docs - Mozilla
If the CORS configuration isn't setup correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same Origin ...
Read more >
Handling CORS | Socket.IO
The complete list of options can be found here. Example with cookies (withCredentials) and additional headers: // server-side
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found