10
14

More than 5 years have passed since last update.

@nuxt/axiosでCRUDする時のアクセス方法とデータの受け取り方【Nuxt + Express】

Posted at

import axios from 'axios' ではなく、@nuxt/axiosnuxt.config.js に modules として登録すること使用できる。
axiosを使いデータベースをCRUDする時の頻出メソッドと、サーバーサイドへの値の渡し方、受け取り方のまとめ。
公式に載っていないものもあったので記載しておきます。
公式はこちら

"@nuxtjs/axios": "^5.3.6",
"body-parser": "^1.19.0",
"express": "^4.16.4",
"nuxt": "^2.0.0",

Create 【$post】

front.vue
this.$axios
  .$post('/',  querystring.stringify({ foo: 'bar' }))
  .then(res => {
    ...
  })
back.js

app.post('/', (req, res) => {
  res.send(req.body.foo) // 'bar'
})

nodeではQueryStringを使ってデータを送ることが推奨されているよう。
QueryStringはnodeの標準で入っているモジュール。
フロントでセットしたデータは、サーバーサイドでreq.bodyで参照できる。(body-parserが必要)
https://github.com/axios/axios#instance-methods
Query String

Read 【$get】

front.vue
this.$axios
  .$get('/', { params: { foo: 'bar' }})
  .then(res => {
    ...
  })
back.js

app.get('/', (req, res) => {
  res.send(req.query.foo) // 'bar'
})

フロントでパラメータをセットした場合、サーバーサイドではreq.queryで参照できる。

Update 【$put】

front.vue
const userId = 123456789

this.$axios
  .$put(`/${userId}`,  querystring.stringify({ foo: 'bar' }))
  .then(res => {
    ...
  })
back.js

app.put('/:id', (req, res) => {
  console.log(req.params.id) //123456789
  res.send(req.body.foo) // 'bar'
})

putメソッドは、サーバーサイドにアクセスする際にidが必要。
サーバー側のパス:idにフロントから送られたidがセットされ、req.paramsで参照できる。

データを送る際はpostメソッドと同じ送り方が使える。

Delete 【$delete】

front.vue
const userId = 123456789

this.$axios
  .$delete(`/${userId}`)
  .then(res => {
    ...
  })
back.js

app.delete('/:id', (req, res) => {
  res.send(req.params.id) // 123456789
})

deleteメソッドもputと同様の送り方でidが必要。

おまけ

Nuxt特有のasyncDataを使ってaxiosを使う際

front.js
async asyncData({ app }) { 
  await app.$axios.$get('/')
    .then(res => {
      ...
    })
}

今回は以上です。
他にもNuxt特有の使い方が多いので、また学習が進み次第まとめます。
補足、修正などありましたらご教授いただけますと幸いです。
最後まで読んでいただきありがとうこざいます。

10
14
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
10
14