PLhery / node-twitter-api-v2

Strongly typed, full-featured, light, versatile yet powerful Twitter API v1.1 and v2 client for Node.js.
https://www.npmjs.com/package/twitter-api-v2
Apache License 2.0
1.32k stars 186 forks source link

CORS issue when authorizing twitter account with Node.js and React.js #535

Open seljad opened 5 months ago

seljad commented 5 months ago

I'm attempting to authorize a Twitter account using the twitter-api-v2 library in a Node.js API connected to a React.js frontend. Here's the Node.js code snippet I'm using:

const { TwitterApi } = require('twitter-api-v2');

module.exports = async (req, res) => {
    const twitterClient = new TwitterApi({
        appKey: process.env.TWITTER_APP_KEY,
        appSecret: process.env.TWITTER_APP_SECRET,
        accessToken: process.env.TWITTER_ACCESS_TOKEN,
        accessSecret: process.env.TWITTER_ACCESS_SECRET,
        bearerToken: process.env.TWITTER_BEARER_TOKEN
    });
    try {
        const { url, oauth_token, oauth_token_secret } = await twitterClient.generateAuthLink('http://127.0.0.1:3000/api/v1/twittercallback');
        req.session.oauth_token = oauth_token;
        req.session.oauth_token_secret = oauth_token_secret;
        res.redirect(url);
    } catch (error) {
        return res.json({
            status : 0,
            message : 'Error generating auth link',
            error : error
        })
    }
}

When I send a request to this API endpoint from my React.js app, the code executes correctly, but I encounter the following error upon redirection in the browser:

Access to XMLHttpRequest at 'https://api.x.com/oauth/authenticate?oauth_token=CIpqTwAAAAABt-2-AAABkAJgN4U' (redirected from 'http://192.168.10.38:3000/api/v1/authtwitter') 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.

Interestingly, when I send the request directly from the browser or Postman, everything works fine.

I'm unsure how to resolve this CORS issue. Any insights or solutions would be greatly appreciated.

PLhery commented 5 months ago

Hello,

It looks like you're doing a FETCH from the API (to ex. read the result as a JSON object) ; and your API instead of replying a JSON object, redirects to Twitter's URL. So you're code tries to FETCH from Twitter's URL, which is forbidden.

Either your API should reply with the URL (instead of redirecting), then your JS would redirect to the URL

Either instead of doing a fetch, redirect users to "http://192.168.10.38:3000/api/v1/authtwitter" and they will be redirected to the right URL, instead of fetching the content from it

Good luck with your project