apollo-client不适用于CORS [英] apollo-client does not work with CORS

查看:173
本文介绍了apollo-client不适用于CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在AWS Lambda上编写graphql服务器组件(不使用graphql-server).在客户端,我正在使用apollo-client.关于lambda函数的响应,我正在设置

I am writing a graphql server component on AWS Lambda (NOT using graphql-server). On the client side I'm using apollo-client. On the response of the lambda function I'm setting

const response = {
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*" // Required for CORS support to work
    },
    body: JSON.stringify({
        result: 'mock data',
        input: event,
    }),
};
callback(null, response);

在使用ApolloClient的客户端上,出现以下错误

On the client side using ApolloClient I get the following error

对预检请求的响应未通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源" http://localhost:8080 .

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

但是,当我使用axios之类的东西执行相同的请求时,它可以正常工作.此外,当我只是通过邮递员执行请求时,响应中启用了"Access-Control-Allow-Origin"设置.这是apollo-client的已知问题,我该如何解决?

However when I execute the same request using something like axios then it works fine. Furthermore when I just execute the request over something like postman I see the "Access-Control-Allow-Origin" setting enabled on the response. Is this a known issue with apollo-client and how do I fix this?

推荐答案

要解决Apollo的CORS问题,您必须将no-cors选项传递给基础fetch.

To workaround the CORS issue with Apollo you have to pass the no-cors option to the underlying fetch.

import ApolloClient from "apollo-boost";

const client = new ApolloClient({
  uri: "your client uri goes here",
  fetchOptions: {
    mode: 'no-cors',
  },
});

这不是特定的Apollo问题,而是要在fetch侧解决的配置,请参见以下详细信息:

This is not a specific Apollo problem, rather a configuration that is meant to be tackled on the fetch side, see this for more information: https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api#cross-origin_requests

我想知道为什么它可以与Axios一起使用,我希望您在某处设置no-cors模式.

I wonder why it does works with Axios for you, I'd expect you to have the no-cors mode set somewhere.

这篇关于apollo-client不适用于CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆