1
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 1 year has passed since last update.

[Nuxt.js]generateしたファイルでaxiosのbaseURLがlocalhostになってしまう問題の対処

Last updated at Posted at 2021-12-27

困ったこと

  • axiosのURLを相対パスで書くとgenerateした静的ファイルでもlocalhostに向けてリクエストを投げてしまう。

    image.png

解決策

  • axiosのbaseURLを書き換えておく。
  this.$axios.defaults.baseURL = window.location.origin

実装例

  • axiosのbaseURLを書き換えるpluginを作成する。
plugins/axios.js
export default function ({ $axios, store, redirect }) {

  // baseURLを書き換えておく
  $axios.defaults.baseURL = window.location.origin

  // ↓は蛇足
  $axios.onRequest((config) => {})
  $axios.onResponse((response) => {})
  $axios.onError((error) => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect("/400")
    }
  })
}
  • 呼び出し用のpluginも作っておく。
plugins/api.js
export default function (obj, inject) {
  const api = new API(obj.$axios, obj.store, obj.redirect)
  inject("api", api)
}

class API {
  constructor(axios, store, redirect) {
    this.axios = axios
    this.store = store
    this.redirect = redirect
  }

  async getRequest(url, params) {
    const res = await this.axios.$get(url, {
      headers: {
        "content-type": "application/json",
      },
      params: params,
    })
    return res
  }

  async postRequest(url, params) {
    const res = await this.axios.$post(url, params, {
      headers: {
        "content-type": "application/json",
      },
    })
    return res
  }
}

  • nuxt.config.js でpluginをロードしておく
nuxt.config.js
  plugins: [
    { src: "@/plugins/axios", ssr: false },
    { src: "@/plugins/api", ssr: false },
  ],
  • 使うときはこんな感じで
 const res = await this.$api.postRequest(
     "/apipath",
     {data: hoge}
 )

参考にさせていただいた記事

(Qiita)Nuxtのaxios-moduleがbaseURLを決定する仕組みの解説と、Netlify FormsへPOSTするときの対策

1
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
1
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?