我在这里使用graphql pyramida后端和最上面的graphql Yoga Express服务器。在前端,我尝试调用退出突变,但被CORS策略阻止。尽管我在我的graphql Yoga服务器中添加了cors设置,但仍然出现此错误。 GraphQL查询工作正常,但突变被阻止。我的前端URL是“ http://localhost:7777”,而Yoga Server正在运行“ http://localhost:4444/”。错误是:
Access to fetch at 'http://localhost:4444/' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
[Network error]: TypeError: Failed to fetch
GraphQL Yoga Server核心配置:
server.start(
{
cors: {
credentials: true,
origin: [process.env.FRONTEND_URL],
},
},
deets => {
console.log(
`Server is now running on port http://localhost:${deets.port}`
);
}
);
突变:
// import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import styled from 'styled-components';
import gql from 'graphql-tag';
import { CURRENT_USER_QUERY } from './User';
import { log } from 'util';
const SIGN_OUT_MUTATION = gql`
mutation SIGN_OUT_MUTATION {
signout {
message
}
}
`;
const SignOutBtn = styled.button`
color: ${props => props.theme.textMedium};
padding: 10px;
margin-right: 20px;
text-align: center;
font-family: garamond-light;
border: 1px solid ${props => props.theme.textMedium};
border-radius: 5px;
transition: background-color 0.5s ease;
transition: color 0.5s ease;
:hover {
background: ${props => props.theme.textMedium};
color: ${props => props.theme.white};
}
`;
const Signout = props => (
<Mutation
mutation={SIGN_OUT_MUTATION}
refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
{signout => (
<SignOutBtn
onClick={() => {
console.log("comes here")
signout();
}}
>
Sign Out
</SignOutBtn>
)}
</Mutation>
);
export default Signout;
请告诉我我在做什么错。预先感谢。
答案 0 :(得分:1)
该问题的解决方案是编写一个设置适当的响应头的中间件,以使提取不会失败。
server.express.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:7777');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
以上是用于解决该问题的Yoga Express服务器中间件。
答案 1 :(得分:1)
添加这种中间件对我的情况有帮助:
server.express.use((req, res, next) => {
res.header('Access-Control-Allow-Credentials', true)
next()
})
答案 2 :(得分:0)
我要做的是将字符串值数组传递给原点。以及在heroku中设置新的原点PAST_FRONTEND_URL
server.start(
{
cors: {
credentials: true,
origin: [process.env.FRONTEND_URL, process.env.PAST_FRONTEND_URL],
},
},
deets => {
console.log(`Server is now running on port http://localhost:${deets.port}`);
}
);
答案 3 :(得分:0)
我遇到了同样的问题,并为此解决了
server.start(
{
cors: {
credentials: true,
origin: [process.env.FRONTEND_URL],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204
}
},
server => {
console.log(`Server is running on http://localhost/${server.port}`);
}
);
答案 4 :(得分:0)
有时 问题是与cors无关,这是后端错误。对我来说,当我将图像上传到服务器时,它会重新加载节点服务器,并且在服务器重新启动期间客户端将不会收到任何访问源标头响应,浏览器会抱怨