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
以降の部分を記述するだけでよくなります。