0

预检(cors)请求服务器将来源更改为 * 后,chrome 不显示请求(但我查看响应正文)。

请求标头

铬的错误:

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'.

我在后端使用 express、cors、graphql、apollo,在前端使用 react。

Cors 配置(后端):

app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true,
    maxAge: 86400,
    optionsSuccessStatus: 200,
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].join(','),
}));

标头配置(前端)

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;
}

如何解决问题?

4

1 回答 1

-1

我只是自己解决了这个问题,这是一场噩梦。它不起作用的原因是 CORS 标头.中必须有一个。http://localhost:3000不符合那个资格。

我通过进入我的主机文件(在 Mac 上:)/etc/hosts并将虚拟域重定向api.myapp.local到 127.0.0.1(本地主机)解决了这个问题。然后我将我的前端重定向到app.myapp.local. 因此,现在当 CORS 请求发出时,它是 from http://app.myapp.local:3000tohttp://api.myapp.local:3001并且它满足该要求。您可以随意调用域。

于 2019-03-05T02:41:53.747 回答