logo
Published on

APIGatewayのpreflight_requestによるエラーについて

Authors

preflight request とは

対処法

APIGateway

  • APIGateway で axios の POST を受けるためには、リソースの method に OPTIONS を加える必要がある。
  • また、適切なヘッダを返す必要がある。例えばこんな感じ。
return {
  'statusCode': 200,
  'headers': {
    "Content-Type": "application/json",
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
  },
  'body': json.dumps(body)
}

axios

  • axios 側はこんな感じにしました。
axios.post(url, data, { headers: { 'Content-Type': 'application/json' } }).then((response) => {
  console.log(response.data)
})