apollo-client does not work with CORS

后端 未结 4 670
北恋
北恋 2021-02-07 14:44

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 sett

4条回答
  •  难免孤独
    2021-02-07 15:35

    here is a working example. the server must have CORS enabled. that means the origin of your http request

    origin: https://example.com

    must match the access-control-allow-origin header of the response to your request.

    access-control-allow-origin: https://example.com

    Then on the Angular client you can use this module:

    import {NgModule} from '@angular/core';
    import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
    import {HttpLinkModule, HttpLink} from 'apollo-angular-link-http';
    import {InMemoryCache} from 'apollo-cache-inmemory';
    import {environment} from 'src/environments/environment';
    import {errorLink} from './dm-core/graphql/apollo-link-error';
    import {concat} from 'apollo-link';
    
    export function createApollo(httpLink: HttpLink) {
        return {
            link: concat(errorLink, httpLink.create({uri: environment.graphql, withCredentials: true})),
            cache: new InMemoryCache(),
            defaultOptions: {
                watchQuery: {
                    errorPolicy: 'all'
                }
            }
        };
    }
    
    @NgModule({
        exports: [ApolloModule, HttpLinkModule],
        providers: [
            {
                provide: APOLLO_OPTIONS,
                useFactory: createApollo,
                deps: [HttpLink]
            }
        ]
    })
    export class GraphQLModule {}
    

    Note the "withCredentials: true":

        link: concat(errorLink, httpLink.create({uri: environment.graphql, withCredentials: true})),
    

提交回复
热议问题