在印前检查(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,在前端使用react。
Cors配置(后端):
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
maxAge: 86400,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].join(','),
}));Header配置(前端)
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;
}如何解决问题?
发布于 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:3000到http://api.myapp.local:3001的,并且它满足该要求。你可以给域名起任何你喜欢的名字。
https://stackoverflow.com/questions/54992222
复制相似问题