微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

“预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段模式”如何解决 Apollo 的问题?

如何解决“预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段模式”如何解决 Apollo 的问题?

当我使用 gql 进行简单的获取请求时,它工作正常,但是当我尝试使用 apollo 客户端进行获取时,它显示错误 Access to fetch at 'bla-bla' from origin 'http: //localhost:3000' 已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段模式。

这是我的 Apollo 客户:

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;

解决方法

在下面更改并尝试...

之前

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

之后

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。