LoginSignup
19
15

More than 3 years have passed since last update.

[初心者向け]VueとExpressを使ってパラメーターの受け渡しをしてみよう

Posted at

はじめまして、PMをやっているtatsukenと申します。はじめまして
研修の一環でvue.js、expressを書くことがあったので、そのことを中心にまとめていきたいと思います.

はじめに

Vue.jsでaxiosを使ってパラメーターをpostしexpressで作った、apiで受取るというところまでやりたいと思います。

必要な環境

Vue.jsの実装

  • まずこちらの記事を参考にしてサーバーを立ち上げてください。
  • http://localhost:8080にアクセスして、このような画面が表示されれば成功です。 スクリーンショット 2019-06-25 20.11.51.png
  • 次にaxiosをインストール
    • npm install axios -s

画面を作る

  • 次にsrc/components/HelloWorld.vueをいかのように書き換えてください
HelloWorld.vue
<template>
  <div class="hello">
    <form action>
      <input type="text" placeholder="text" v-model="text">
      <input type="submit" value="decide" @click="submitClick">
    </form>
  </div>
</template>

画面はこのようになっています
スクリーンショット 2019-06-25 20.36.00.png

HelloWorld.vueの</template>以下に<script>を追加

HelloWorld.vue
<script>
import Axios from "axios";
export default {
  name: "HelloWorld",
  data() {
    return {
      text: null
    };
  },
  methods: {
    submitClick() {
      alert(this.text)
    }
  }
};
</script>

このようにinputに文字を入力してその文字がalertに表示されれば成功です
スクリーンショット 2019-06-25 20.42.23.png

<script></script>を書き換え

次に<script></script>を以下のように書き換えてください

HelloWorld.vue
<script>
import Axios from "axios";
export default {
  name: "HelloWorld",
  data() {
    return {
      text: null
    };
  },
  methods: {
    submitClick() {
      const body = {
        text: this.text
      };
      Axios.get(`http://localhost:3000/hoge/${this.text}`)
        .then(res => {
          console.log(res.data.name)
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

Expressの実装

簡単なapiを作ってみる

  • アプリ名/app.jsに以下のことを追記しましょう
app.js
app.get('/hoge', (req, res) => {
  res.json({
    name: "hoge"
  })
});

スクリーンショット 2019-06-25 21.03.04.png

apiを書き換える

app.js
app.get('/hoge/:name', (req, res) => {
  let data = req.params
  console.log(data.name);
  res.json({
    name: data.name
  })
});

これでコードを書く部分はすべて終了です。

動かしてみる

  • http://localhost:8080にアクセスし任意の文字を入力し送信してください。

  • Expressを動かしているconsole上にfrontから送信した文字が表示されていれば成功です
    スクリーンショット 2019-06-25 21.25.26.png
    スクリーンショット 2019-06-25 21.25.38.png

最後に

初心者向けにVue.jsからExpressのapiへのパラメーターの受け渡しを行いました。
これから始める方の手助けになれば幸いです。
なにか間違いがあればご連絡ください。

19
15
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
19
15