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

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,
}))


如果我这样做,则飞行前选项成功,但实际的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。

尝试使用快递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 ) );

07-28 01:43
查看更多