34
33

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 5 years have passed since last update.

Nuxt.jsのメソッド内で外部APIを叩くとcorsエラーが起きる

Last updated at Posted at 2019-06-11

環境

nuxt 2.8.1
@nuxtjs/axios: 5.3.6

問題

asyncDataだとできるのに

asyncData({ app, params, store }) {
    const data = {key: "value"}
    return app.$axios.$post([URL], data
    ).then(res => {
      console.log(res)
    })
  },

普通のメソッドだとできない

getData: function(data) {
      const res = this.$axios.$post([URL], data
      ).catch(error => {
        console.log(error)
      })
      
      
//結果
// Access to XMLHttpRequest at [URL] from origin 'http://localhost:3000' has been blocked by CORS policy: 
// Response to preflight request doesn't pass access control check: 
// No 'Access-Control-Allow-Origin' header is present on the requested resource.      

理由:

asyncData() では、SSRにより表示を行うため、Proxyを挟まなくてもデータを取得できるため。

参考にした記事

SSR(ServerSideRendering)についてはこちらの記事が参考になりました。
React での ServerSideRendering 入門

解決方法

Proxyを導入しました。
@nuxtjs/axiosにある機能を使用し、以下の設定をした後、全てのエンドポイントの冒頭に /api/ をつけました。

nuxt.config.js
...
modules: [
    '@nuxtjs/axios'
  ],

  axios: {
    proxy: true
  },
  proxy: {
    '/api/': {target: 'YOUR API URL', pathRewrite: {'^/api/': '/'}}
  },
  plugins: [
    { src: 'plugins/axios.js', ssr: false }
  ],
...
plugins/axios.js
export default function({ $axios, redirect }) {
  $axios.setToken('access_token')

  $axios.onResponse(config => {
    $axios.setHeader('Access-Control-Allow-Origin', 'YOUR API URL')
  })
}

【参考記事】

34
33
1

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
34
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?