Search code examples
node.jsreactjsapihttp-status-code-400

Why does Twitter API call work fine in Node.js but result in a 400 Error in ReactJS?


I'm running into a constant issue when developing in ReactJS, which is that my API calls result in 400 Bad Request errors, even though the code works fine outside of ReactJS.

Below is (A) code that runs fine locally on NodeJS, and (B) the same code in a React environment. (The dependencies have been installed in both cases.) The (A) NodeJS code runs perfectly fine, but the (B) React code yields the error:

Failed to load https://api.twitter.com/oauth2/token?grant_type=client_credentials: Response for preflight has invalid HTTP status code 400.

(A) Code run in Node.js:

var getBearerToken = require('get-twitter-bearer-token')
var Twitter = require('twitter');

var key = ENV.KEY;
var secret = ENV.SECRET;

getBearerToken(key, secret, (err, res) => {
  if (err) {
    // handle error
  } else {
    var client = new Twitter({
      bearer_token: res.body.access_token,
    });
    client.get('search/tweets', {q: '#WorldCup'}, function(error, tweets, response) {
      console.log(tweets);
    });
  }
})

(B) The exact same code run in ReactJS:

import React, { Component } from 'react';

var getBearerToken = require('get-twitter-bearer-token')
var Twitter = require('twitter');

export default class StockTwitter extends Component {

    componentDidMount() {
      this.setTwitter();
    }

    setTwitter() {

      var key = ENV.KEY;
      var secret = ENV.SECRET;

      getBearerToken(key, secret, (err, res) => {
        if (err) {
          // handle error
        } else {
          var client = new Twitter({
            bearer_token: res.body.access_token,
          });
          client.get('search/tweets', {q: '#WorldCup'}, function(error, tweets, response) {
            console.log(tweets);
          });
        }
      })
    }

    render() {
      return (
        <div>TBD</div>
      )
    }
}

Solution

  • Express builds a server with API and routing, you can make the call to twitter on your express server and then call through your frontend to your own backend.

    Some may call it a proxy server

    Scotch IO Tutorial, express and routes, it's decent

    Here is an example build, forked on github with your code in it working: hcra twitter build. Haven't pulled the tweets through and displayed them or anything, but they do load. The rest is up to you, let me know if you have trouble building or running anything.

    Oh yeh you will need to pull it down run git fetch and then checkout twitter-req branch.