Reena Verma
Reena Verma

Reputation: 1685

ReactJS - Simple Server Side API Request

I'm making a very simple API axios.get request in ReactJS, client side. However, it gets blocked by CORS in my browser. So no data gets returned.

I understand I need to make this request server side, but I'm not sure how I should restructure my code below, (to be written server side).

Any tips on how to rewrite this code, would be much appreciated!

Thanks,

  // MAKE JOB API REQUEST
  componentDidMount() {
    console.log('COMPONENT DID MOUNT');
    axios.get('https://jobs.github.com/positions.json?search=')

      .then(res => {
        console.log('jobs', res.data.slice(0, 9));

        this.setState(
          { jobs: res.data.slice(0, 9) }
        );
      });
  }

Upvotes: 0

Views: 1728

Answers (1)

devserkan
devserkan

Reputation: 17608

As explained in the comments, you need to create a route for that and use proxy to handle the requests. Here is the steps:

webpack.config.js

devServer: {
    contentBase: ['src'],
    watchContentBase: true,
    historyApiFallback: true,
    hot: true,
    inline: true,
    port: 8000,
    open: true,
    proxy: {
      '/api/*': {
        target: 'http://localhost:4000/',
        secure: false
      }
    }
  },

index.js

const axios = require( "axios" );

...skipped codes

app.get( "/api/jobs", ( req, res ) => {
  axios.get( `https://jobs.github.com/positions.json?search=${ req.query.job }` )
    .then( result => res.send( result.data ) );
} );

You need to require axios in this file also as you see.

app.js

handleSubmit = ( e ) => {
    e.preventDefault();
    const { searchData } = this.state;

    axios.get( `/api/jobs?job=${ searchData }` )
      .then( res => this.setState( { jobs: res.data } ) );
}

There was no componentDidMount in your code so I used handleSubmit. With this setup whenever you made a request to /api/something it redirects to your Express server. So, on the front-end you will use /api and you will add the needed routes to your Express setup.

Upvotes: 1

Related Questions