0

I have an error : "Access to fetch at 'http://localhost:4000/' from origin 'http://localhost:3000/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." my server is:

import { GraphQLServer } from 'graphql-yoga'
import { prisma } from './generated/prisma-client'
import resolvers from './resolvers'

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: request => ({
    ...request,
    resolverValidationOptions: { requireResolversForResolveType: false,},
    prisma,
  }),
opt:{
  cors:{
     credentials: true,
     origin:{['http://localhost:3000/']}
}
}
})

server.start(opt,() => console.log(`Server is running on http://localhost:4000`)); 

and my client is :

import { ApolloProvider } from 'react-apollo'
import ApolloClient from 'apollo-client'
import {BrowserRouter} from 'react-router-dom'
import { setContext } from 'apollo-link-context'
import { AUTH_TOKEN } from './constants'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory';
import history from './history';
import { onError } from "apollo-link-error";
import { SnackbarProvider, useSnackbar } from 'notistack';
const httpLink = createHttpLink({
    uri: 'http://localhost:4000/',
});

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem(AUTH_TOKEN);
    return {
        headers: {
            'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
            "Access-Control-Allow-Credentials" : true,
            'Access-Control-Allow-Origin': "http://localhost:3000/",
            authorization: token ? `Bearer ${token}` : ''
        }
    }
});
const linkError = onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors)
        graphQLErrors.map(({ message, locations, path }) =>
            console.log(
                `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
            ),
        );

    if (networkError) console.log(`[Network error]: ${networkError}`);
});
const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),linkError,
        fetchOptions: {
          mode: 'cors',
        },
    });

ReactDOM.render(
    <BrowserRouter>
    <ApolloProvider client={client}>
      <SnackbarProvider>
        <App />
       </SnackbarProvider>
    </ApolloProvider>
    </BrowserRouter>,
    document.getElementById('root'),
);

Please, help me to find a mistake, I looked at different information, and nothing had helped. Thank you

  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Feb 28 '20 at 07:59
  • @sideshowbarker I did. I use it and the status is (failed) type : fetch Response : failed to load response data (Google Chrome) – Natali Hachok Feb 28 '20 at 08:09
  • have you tied with `credentials:false` on server side and `const httpLink = createHttpLink({ uri: 'http://localhost:4000/',withCredentials:false });` – Himanshu Bansal Feb 28 '20 at 08:24
  • @HimanshuBansal I just tried, it doesn't work. The same error – Natali Hachok Feb 28 '20 at 08:54
  • It looks like `GraphQLServer` doesn't take the `CORS` options in its constructor, it's the `server.start` method that does. Also, have you tried getting rid of the `CORS` options or setting them to `null`? And try getting rid of the `fetchOptions` in the `new ApolloClient`, and you don't need those `Access-Control-Allow-*` headers in the `setContext` function. – goto Feb 28 '20 at 09:45
  • @goto1 I just tried your solution and it started to work only when I delete everything that you told me also i set credentials:false into server and withCredentials:false - client. But it still has the error after 30 minute of using. I am curious why it can happen.Could it be a problem with cache? – Natali Hachok Feb 28 '20 at 11:42
  • Not sure what you mean by "30 minute of using", you mean that you're getting `CORS` errors for things that you we're not getting before? Or are you trying something different and then running into an issue? – goto Feb 28 '20 at 11:47
  • @goto1 I mean If to login in (the CORS error is not there), and after sign out. And if to login in again the CORS error is again there. 30 minutes I wrote because it is a middle time of using the web page – Natali Hachok Feb 28 '20 at 11:57
  • Not quite sure how this is even possible unless you're doing some other actions next time you log in. I'd look at the network tab in your browser and see which exact action/call is causing those `CORS` issues, then go from there. – goto Feb 28 '20 at 13:41
  • @goto1 here is the web page where i try to correct the error...just try to put any information and you will get the error (test it few times). thank you – Natali Hachok Feb 28 '20 at 18:02
  • @NataliHachok no link? – goto Feb 28 '20 at 18:34
  • @goto1 sorry, i did not see .. https://metrologistnsnd-beta-frontend.herokuapp.com/login – Natali Hachok Feb 28 '20 at 18:41
  • @NataliHachok unfortunately I can't quite reproduce. – goto Feb 29 '20 at 18:53

0 Answers0