6

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

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

4

5 回答 5

3

该问题的解决方案是编写一个中间件来设置适当的响应标头,以便获取不会失败。

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服务器中间件。

于 2018-12-20T07:19:52.930 回答
1

我有同样的问题,并解决了这个

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}`);
  }
);
于 2019-07-19T07:35:26.847 回答
1

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

您可以使用中间件来实现它。

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 可能存在一些问题,阻止了某些请求。:)

于 2019-12-14T19:40:21.077 回答
1

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

于 2019-03-14T00:19:15.253 回答
1

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

server.express.use((req, res, next) => {
  res.header('Access-Control-Allow-Credentials', true)
  next()
})
于 2019-09-16T19:43:13.763 回答