1

I'm having a problem with node.js apparently ignoring my cors settings. Here are my repos: Backend Frontend

The culprit code in backend:

...
//config.CLIENT_URL is 'http://localhost:3000'

const corsOptions: cors.CorsOptions = {
        origin: [String(config.CLIENT_URL)],
        credentials: true,
    };
    app.use(cors(corsOptions));
...

Apollo implementation

//config.BACKEND_URL_DEV is 'http://localhost:4000/graphql/'
function create (initialState, { getToken }) {
  const httpLink = createHttpLink({
    credentials: "include",
  uri: `${config.BACKEND_URL_DEV}`,
  })

  const authLink = setContext((_, { headers }) => {
    let token = getToken()
    return {
      headers: {
        ...headers,
        cookie: token ? token : ''
      }
    }
  })

  return new ApolloClient({
    connectToDevTools: process.browser,
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    link: authLink.concat(httpLink),
    cache: new InMemoryCache().restore(initialState || {})
  })
}

When I go to http://localhost:3000/dashboard where I have my query that I know will execute if I'm logged in via graphql playground this is the message I receive:

enter image description here

Funny enough data is received but CORS is preventing it from displaying. Tested on Opera, Chrome and Firefox DevEdition

enter image description here

It looks like my backend is setting * to Access-Control-Allow-Origin if the request origin domain is correct.

enter image description here

Any insight on this matter is greatly appreciated!

1 Answers1

2

Turns out the problem was with passing cors configuration to apollo-server-express because app.use(cors(corsOptions)) does really nothing for this kind of setup.

CORRECT ANSWER: Move cors config to this section:

apolloServer.applyMiddleware({ app, cors: corsOptions });

Found answer thanks to this stack thread