CORS 阻止 GraphQL Yoga 中的突变

CORS blocks mutation in GraphQL Yoga

我在这里使用 graphql prisma 后端和 graphql yoga express 服务器。在前端,我试图调用注销突变,但它被 CORS 策略阻止了。尽管我在我的 graphql 瑜伽服务器中添加了 cors 设置,但我一直收到此错误。 GraphQL 查询工作正常,但突变被阻止。我的前端 URL 是“http://localhost:7777' and yoga server is running at '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 服务器 Cors 配置:

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;

请告诉我我做错了什么。提前致谢。

问题的解决方案是编写一个中间件来设置适当的响应headers,这样获取就不会失败。

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 server中间件

我必须做的是向原点传递一个字符串值数组。以及在 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}`);
  }
);

我遇到了同样的问题,这个

解决了
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}`);
  }
);

添加这个中间件对我的情况有帮助:

server.express.use((req, res, next) => {
  res.header('Access-Control-Allow-Credentials', true)
  next()
})

服务器应用程序必须将 Access-Control-Allow-Origin: YOUR_DOMAIN 添加到响应 header 并且浏览器不会抱怨它。

可以使用中间件来实现

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

const cors =  require('cors')
const corsOptions = {
    origin: [
        
        "http://YOUR-DOMAIN"
    ],
    credentials: true
}
app.use(cors(corsOptions))

但是等等!!我已经完成了这些步骤,但问题仍然存在;(

如果在这些步骤之后问题仍然存在。

那是因为错误的响应

也许您的服务器在发送响应时抛出异常,或者可能重新启动并且响应没有完全发送给客户端。或者您的 ISP 或 VPN 可能会阻止某些请求。 :)