阿波罗客户端不适用于 CORS [英] apollo-client does not work with CORS

查看:33
本文介绍了阿波罗客户端不适用于 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"标头.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 端解决的配置,有关更多信息,请参阅:https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api#cross-origin_requests

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.

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

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