Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

reactjs - "Request header field mode is not allowed by Access-Control-Allow-Headers in preflight response" how to solve problem with Apollo?

When i make simple fetch request with gql it works fine, but when I try to make it with apollo client it shows this error Access to fetch at 'bla-bla' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field mode is not allowed by Access-Control-Allow-Headers in preflight response.

This is my Apollo client:

import {
  ApolloCache,
  ApolloClient,
  HttpLink,
  InMemoryCache,
  concat,
  NormalizedCacheObject,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

const createApolloClient = (isServer: boolean) => {
  const httpLink = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL });
  const accessToken = localStorage.getItem(
    "CognitoIdentityServiceProvider.653kt2v1novmi53toi3uc82m4f.Google_112862354108088073641.accessToken"
  );

  const authLink = setContext(async (_, { headers }) => {
    return {
      headers: {
        ...headers,
        mode: "no-cors",
        "Access-Control-Allow-Origin": "*",
        'Authorization': accessToken,
      },
    };
  });

  const cache = new InMemoryCache({}).restore(
    !isServer ? (window as any).__APOLLO_STATE__ : {}
  ) as ApolloCache<NormalizedCacheObject>;

  const client = new ApolloClient<NormalizedCacheObject>({
    cache,
    defaultOptions: {
      watchQuery: {
        fetchPolicy: "cache-first",
      },
    },
    link: concat(authLink, httpLink),
    ssrMode: isServer,
    ssrForceFetchDelay: isServer ? 100 : undefined,
  });

  return client;
};

export default createApolloClient;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change below and try...

before

  const authLink = setContext(async (_, { headers }) => {
    return {
      headers: {
        ...headers,
        mode: "no-cors",
        "Access-Control-Allow-Origin": "*",
        'Authorization': accessToken,
      },
    };
  });

After

const authLink = setContext(async (_, { headers }) => {
    return {
        headers: {
            ...headers,
            mode: "no-cors",
            "Access-Control-Allow-Origin": "*",
            'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
            "Access-Control-Allow-Credentials": true,
            'Authorization': accessToken,
        },
    };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...