2
votes

Stumped on a CORS issue while attempting to integrate GraphQL into a ReactJS application.

Situation:

I'm trying to execute a simple graphql query. No use of a database. The program works fine without graphql implementation.

Browser: Google Chrome Version 78.0.3904.87

Computer: MacBook Pro, Mid-2015

Relevant dependencies:

  • apollo-boost: 0.4.4
  • apollo-client: 2.6.4
  • cors: 2.8.5
  • express: 4.17.0
  • graphql: 14.5.8
  • react: 16.8.6
  • react-apollo: 3.1.3

Here's the error I'm getting in the browser console:

OPTIONS http://localhost:5000/graphql net::ERR_CONNECTION_REFUSED

See the repository/directory structure here:

https://github.com/curtisyungen/hh-graphql

Here's a look at my server.js file:

const express = require("express");
const graphqlHTTP = require('express-graphql');
const schema = require('./src/graphql/schema');
const cors = require('cors');

const PORT = 5000;

const app = express();

app.use(cors());
app.use('/graphql', graphqlHTTP({
    schema, 
    graphiql: true,
}));

app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}. Visit http://localhost:${PORT}/ in your browser.`);
});

module.exports.app = app;

Here's how I'm setting up the Apollo Client in my App.js file:

const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'http://localhost:5000/graphql'
});

const client = new ApolloClient({
  cache,
  link,
});

Here is a screenshot of the Network tab in the browser:

Screenshot of Network Tab in Browser

I've scoured the internet for solutions and have tried the following:

  • app.use(cors());
  • adding fetchOptions: { mode: 'no-cors' } to Apollo Client
  • adding Access-Control-Allow-Origin extension to Chrome
  • using local IP address in lieu of 'localhost'

I was following a YouTube tutorial where the guy solved this issue by importing cors. It worked for him but not for me...any ideas?

1
Can you share your directory structure ?Ozan Manav
@OzanManav you can see the repo here: github.com/curtisyungen/hh-graphqluser18169

1 Answers

0
votes

The problem here, you are calling an API from your reactjs frontend.

And your backend is not configured to accept connections from different domain calls.

you need to allow that on your server by adding the relevant headers to your server config.

Or, in your reactjs package.json add the below lines

"proxy": "http://localhost:5000", # should be the base api url path 

You can check an article I wrote about the issue here https://minasami.com/2021/06/10/cors-errors-fix-with-reactjs.html