How to enable the CORS mode on frontend side in GraphQL/AWS Amplify?

866 views Asked by At

How to do same for GraphQL of AWS Amplify?

fetch('https://trusted-api.co.jp', {
  mode: 'cors'
});

I did not found neither the documentation how to do it nor source code which mention to cors.

Reference

Regular graphQL operation could be called as below:

import AWSAmplifyAPI, { graphqlOperation as graphQL_Operation, GraphQLResult } from "@aws-amplify/api";
import Observable from "zen-observable";

export default class DataBaseService {

  public static async sendRequestAndExtractDataFromResponse(
      graphQL_RawRequest: string,
      requestVariables?: object
  ): Promise<unknown> {

    const serverRawResponse: GraphQLResult | Observable<unknown> =
        await AWSAmplifyAPI.graphql(graphQL_Operation(graphQL_RawRequest, requestVariables));
   // ...
  }
}
1

There are 1 answers

0
Xin On BEST ANSWER

You need to configure this on the server side, so the server side needs to approve this "CORS" issue.

Technically your amplify lambda function would add the code similar to:

exports.handler = async (event) => {
  const response = {
    statusCode: 200,
    //  Uncomment below to enable CORS requests
    headers: {
      "Access-Control-Allow-Origin": "*",
    },

    //   headers: {
    //     "Access-Control-Allow-Headers" : "Content-Type",
    //     "Access-Control-Allow-Origin": "https://www.example.com",
    //     "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
    // },
    body: JSON.stringify("Hello from Lambda!"),
  };
  return response;
};