3
1

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.

AxiosでAPIのエンドポイントを@nuxtjs/proxyを使って省略する

3
Last updated at Posted at 2020-09-06

Axiosを使ってAPI実行する時にエンドポイントを全て書くのはめんどくさいですよね。

具体的にどういうことかというと、
こういうことです。

プロキシ未設定

index.js
async fetchData({ commit, state }) {
  try {
    const resp = await this.$axios.$get('http://localhost:8000/api/score')
    commit('setData', resp)
  } catch (error) {
    console.log(error)
  }
}

プロキシ設定済

index.js
async fetchData({ commit, state }) {
  try {
    const resp = await this.$axios.$get('/api/score')
    commit('setData', resp)
  } catch (error) {
    console.log(error)
  }
}

APIのエンドポイントが短くなっていますね。

このやり方を解説します。

@nuxtjs/proxyをインストール

npm install --save @nuxtjs/proxy

proxyの設定

nuxt.config.jsに下記の設定を追加します。

nuxt.config.js
modules: [
  '@nuxtjs/proxy'
],
proxy: {
  '/api': 'http://localhost:8000'
}

※8000のところは各自のサーバのものを入れてください。
これで設定完了です。

あとはAxios使う時のAPIエンドポイントは
http://localhost:8000
以降の部分を記述するだけでよくなります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?