After preflight (cors) request server change origin to * and chrome not display request (but i look response body).
Chrome's error:
Access to fetch at 'http://localhost:6529/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
I use express, cors, graphql, apollo on backend and react on frontend.
Cors configuration (backend):
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
maxAge: 86400,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].join(','),
}));
Headers configuration (frontend)
const credentials = "include";
let client: ApolloClient<NormalizedCacheObject> | null = null;
export function createClient(cookie: any, ctx: any, store: any): ApolloClient<NormalizedCacheObject> {
storage.setItem("ctx", ctx);
client = new ApolloClient({
cache,
link: ApolloLink.from([
onError(({graphQLErrors, networkError}) => {
if (graphQLErrors) {
if (!SERVER) {
const redirectUrl = getRedirect(graphQLErrors);
if (redirectUrl) {
location.assign(redirectUrl);
}
}
graphQLErrors.map(({message, locations, path}) => {
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
);
});
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
}),
new ReduxLink(store),
new BatchHttpLink({
credentials,
uri: GRAPHQL,
headers: cookie,
fetchOptions: {
withCredentials: true,
credentials,
},
}),
],
),
ssrMode: SERVER,
connectToDevTools: true,
});
return client;
}
How to solve a problem?
I just went through the problem myself and it was a nightmare. The reason it is not working is that the CORS header must have a
.
in it.http://localhost:3000
doesn't meet that qualification.I solved this issue by going into my host's file (on a Mac:
/etc/hosts
) and redirecting a dummy domain such asapi.myapp.local
to 127.0.0.1 (localhost). Then I redirected my frontend toapp.myapp.local
. So now when the CORS request is made it is fromhttp://app.myapp.local:3000
tohttp://api.myapp.local:3001
and it meets that requirement. You can call the domain whatever you would like.