【问题标题】:How to make Graphql run with CORS如何使 Graphql 与 CORS 一起运行
【发布时间】:2017-11-23 10:47:24
【问题描述】:

我已经阅读了几篇关于此的文章,但没有一篇对我有用。

https://github.com/graphql/express-graphql/issues/14

这是我的 expressjs 代码:

app.use("/graphql", function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});


// apply graphql middleware
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: rootResolver,
  graphiql: true,
}))

如果我这样做的话,pre-flight OPTIONS 是成功的,但是实际的 POST 请求失败了。

我正在使用此函数向本地 graphql 服务器发出请求。

function postFn(url, payload) {
  return $.ajax({
    method: 'POST',
    url: url,
    contentType: 'application/json',
    xhrFields: {
      withCredentials: true
    },
    data: payload
  });
}

这里是触发POST请求的前端代码:

  let query = `
    query myqury($offset: Int, $limit: Int) {
      clients(limit:$limit , offset:$offset ) {
        docs{
          _id
          full_name
        }
        total
        limit
        offset
      }
    }
  `
  var variables = {
    offset: offset,
    limit: limit
  }
  let payload = {
    query: query,
    variables: variables
  }
  return request.post(graphQlEndpoint, payload)

错误信息是:

请求的资源上没有“Access-Control-Allow-Origin”标头

【问题讨论】:

    标签: graphql


    【解决方案1】:

    我在使用 Vue 客户端拨打电话时遇到了同样的问题。我可以解决的唯一方法是禁用浏览器上的跨域限制以进行测试。

    【讨论】:

      【解决方案2】:

      请在您的 server.js 文件中插入以下代码

      const graphQLServer = express();
      const corsOptions = {
          origin(origin, callback) {
              callback(null, true);
          },
          credentials: true
      };
      graphQLServer.use(cors(corsOptions));
      var allowCrossDomain = function(req, res, next) {
          res.header('Access-Control-Allow-Origin', '*');
          res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
          res.header('Access-Control-Allow-Headers', 'Content-Type,token');
          next();
      }
      graphQLServer.use(allowCrossDomain);

      我认为这可能会解决您的问题

      【讨论】:

      • 除非这是一个公共 API,否则禁用所有 CORS 安全性(此答案建议)是一个很大的安全风险。
      • cors 定义在哪里?
      【解决方案3】:

      我和你有同样的问题。在快速服务器上使用 graphQL。

      尝试使用快递cors

      像这样在你的快速代码中使用它

      const express = require( `express` );
      const graphqlHTTP = require( `express-graphql` );
      const cors = require( `cors` );
      const app = express();
      
      app.use( cors() );
      app.use(
          `/graphql`,
          graphqlHTTP( {
              schema: schema, // point to your schema 
              rootValue: rootResolver, // point to your resolver 
              graphiql: true
          } )
      );

      基于GraphQL Documentation获取示例

      fetch( url, {
          method : `post`,
          headers: {
              'Content-Type': `application/json`,
              'Accept'      : `application/json`
          },
          body: JSON.stringify( {
              query: `
              {
                  person {
                      name
                  }
              }`
          } )
      } )
      .then( response => response.json() )
      .then( response => console.log( response ) );

      【讨论】:

      • 对引号的兴趣选择(反引号模板而不是字符串文字)但是很好的答案,我只是把 cors() 放进去,嘿嘿!多么美好的一天
      • 我通常只使用反引号,不知道为什么我在这种情况下使用单引号。但这意味着我可以轻松使用 es6 字符串插值
      猜你喜欢
      • 2021-08-14
      • 2020-01-09
      • 2016-09-24
      • 2016-09-19
      • 2020-05-29
      • 2013-07-02
      • 2021-06-11
      • 2020-10-21
      • 2019-04-29
      相关资源
      最近更新 更多