飞行前(cors)请求服务器将原产地更改为*并且chrome不显示请求(但我看起来是响应正文)。
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,并在前端进行反应。
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;
}
如何解决问题?
答案 0 :(得分:0)
我本人只是经历了这个问题,这是一场噩梦。它不起作用的原因是,CORS标头中必须包含.
。 http://localhost:3000
不符合该条件。
我通过进入主机文件(在Mac:/etc/hosts
上)并将诸如api.myapp.local
之类的虚拟域重定向到127.0.0.1(localhost),解决了此问题。然后,我将前端重定向到app.myapp.local
。因此,当发出CORS请求时,它是从http://app.myapp.local:3000
到http://api.myapp.local:3001
,并且满足该要求。您可以随意拨打该域。