简体   繁体   中英

How to override AWS Amplify Api domain endpoint

I have added a custom domain to the API Gateway due to CORS/Cookies/Infosec and other fun reasons.

I then added the following code to hack the correct domain into my Amplify configuration:

import { Amplify, API } from "aws-amplify"

const myfunc () => {
  const amplifyEndpoint = API._restApi._options.endpoints[0]
  Amplify.configure({
    aws_cloud_logic_custom: [
      {
        ...amplifyEndpoint,
        endpoint: process.env.REACT_APP_API_URL || amplifyEndpoint.endpoint,
      },
    ]
  })

  const response = await API.post("MyApiNameHere", "/some-endpoint", {data:"here"})
}

This works but a) is this really the correct way to do it? and b) I'm seeing a weird issue whereby the first API.post request of the day from a user is missing the authorization & x-amz-security-token headers that I expect Amplify to be magically providing. If a user refreshes the page, the headers are sent and everything works as expected.

[edit] turns out my missing headers issue is unrelated to this override, so still need to get to the bottom of that!

The more correct place looks to be in the index.js :

import { Amplify, API } from "aws-amplify"
import awsExports from "./aws-exports"

Amplify.configure(awsExports)

const amplifyEndpoint = API._restApi._options.endpoints[0]
Amplify.configure({
  aws_cloud_logic_custom: [
    {
      ...amplifyEndpoint,
      endpoint: process.env.REACT_APP_API_URL || amplifyEndpoint.endpoint,
    },
  ]
})

That way it's done once - rather than needing to be done in each API call.

Naturally you would need some more complicated logic if you were dealing with multiple endpoints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM