如何让 Graphql 与 CORS 一起运行

Nic*_*.Xu 7 graphql

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

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,
}))
Run Code Online (Sandbox Code Playgroud)

如果我这样做,则飞行前 OPTIONS 成功,但实际 POST 请求失败。

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

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

下面是触发 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)
Run Code Online (Sandbox Code Playgroud)

错误信息是:

请求的资源上不存在“Access-Control-Allow-Origin”标头

Lle*_*ins 5

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

尝试使用 Express 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
    } )
);
Run Code Online (Sandbox Code Playgroud)

基于GraphQL 文档获取示例

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 ) );
Run Code Online (Sandbox Code Playgroud)


小智 0

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