0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.js+axiosでCORSを回避する方法(本番環境, proxyを使わない方法)

Posted at

したいこと

  • フロント(Nuxt.js)からAPIを呼ぶ際に、普通に呼ぶとCORSのエラーになるので回避したい

試したこと(ローカル環境)

にもあるように、proxyを設定していた。

nuxt.config.ts:

  axios: {
    proxy: true
  },

  proxy: {
    '/api/': {
      target: 'https://hoge.co.jp/v1/',
      changeOrigin: true
    },
  }

APIの呼び出し:

await axios.get(
'/api/xxx
)

これで、yarn devしてlocalhostで確認していた際は、うまく行っていた。

問題点

  • 上記の設定でyarn generate したものをサーバー上(AWS)にデプロイしたら、再びCORSエラーになった。

解決方法

  • axiosのヘッダーにCORSの設定を追加した

設定例:

plugin/axios.ts

import { Context } from '@nuxt/types'
import axios from 'axios'

export default function ({ $axios }: Context) {
  $axios.onRequest((config: any) => {
    axios.defaults.headers.common.Authorization = localStorage.getItem(
      'auth._token.local'
    )
    axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*'
    return config
  })
}

所感

  • proxyの設定ができたほうが、APIを呼び出す際に、/apiとかで呼び出せるので、URLがnuxt.config.ts内で完結するのが良さそうだと感じたが、その恩恵を受けられないのが少し残念。

  • 改善に期待

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?