首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在印前检查(cors)请求后,服务器将源更改为*,并且chrome不显示请求(但我查看响应正文)。如何解决问题?

在印前检查(cors)请求后,服务器将源更改为*,并且chrome不显示请求(但我查看响应正文)。如何解决问题?
EN

Stack Overflow用户
提问于 2019-03-05 06:00:36
回答 1查看 522关注 0票数 0

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

Request headers

Chrome的错误:

代码语言:javascript
复制
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配置(后端):

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

Header配置(前端)

代码语言:javascript
复制
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;
}

如何解决问题?

EN

回答 1

Stack Overflow用户

发布于 2019-03-05 10:41:54

我自己也经历过这个问题,简直就是噩梦。它不工作的原因是CORS报头中必须有一个.http://localhost:3000不符合这个条件。

我解决了这个问题,方法是进入我主机的文件(在Mac上:/etc/hosts),并将一个虚拟域名(如api.myapp.local )重定向到127.0.0.1 (本地主机)。然后我将我的前端重定向到app.myapp.local。因此,现在当CORS请求发出时,它是从http://app.myapp.local:3000http://api.myapp.local:3001的,并且它满足该要求。你可以给域名起任何你喜欢的名字。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54992222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档