【问题标题】:GraphQL CORS No 'Access-Control-Allow-Origin' headerGraphQL CORS 没有“Access-Control-Allow-Origin”标头
【发布时间】:2018-08-30 22:20:48
【问题描述】:

在尝试发出 GraphQL 请求时,我收到以下 error

我正在端口 3002 上运行 express 服务器。我还在使用 "/graphql" 端点的 express 服务器上运行 express-graphql。

我正在使用 react 应用程序中的 apollo-client。

我在我的快速代码中尝试了以下内容

app.use(cors())

但是我仍然在客户端上遇到同样的错误

如何解决这个 CORS 问题?

【问题讨论】:

  • 在 google chrome 的控制台尝试 doin fetch("your_graphql_url") 你会看到不同的错误

标签: cors apollo-client express-graphql


【解决方案1】:

在 node.js 上的 ExpressJS 应用中,对路由执行以下操作:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

【讨论】:

    【解决方案2】:

    确保 app.use(cors()) 在使用 graphQL 之前出现。

    快递代码

    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 ) );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-13
      • 2018-09-19
      • 2019-06-19
      • 2017-04-15
      • 2014-01-20
      • 2019-02-07
      • 2016-01-21
      • 1970-01-01
      相关资源
      最近更新 更多