クイズサイト構築の第1回目となります。
目次サイトは下記ページとなります。
準備
$ node -v v12.4.0 $ npm -v 6.10.3 $ vue -V 2.9.6
初期構築
プロジェクトディレクトリの作成
# mkdir spa_test # cd spa_test/
クライアントサイド – Vue.jsのインストール
# yum update # npm install -g @vue/cli-init # vue init webpack frontend →vue-router は有効化 # cd frontend/config index.jsの以下を変更 localhost node.home.local ※firewalldが動作していたらしかるべき処置をする # npm run dev httpアクセス →OK
サーバサイド – expressのインストール
# cd spa_test/ # mkdir backend # cd backend/ # npm init # npm install --save nodemon express body-parser cors # vim package.json ↓に変更 "scripts": { "start": "./node_modules/nodemon/bin/nodemon.js index.js" }, # vim index.js const express = require('express') const bodyParser = require('body-parser') // corsポリシーに抵触するため、その対策としてcorsを利用する const cors = require('cors') const app = express() app.use(bodyParser.json()) app.use(cors()) app.get('/test', function(req, res) { res.send({ message: 'Hello world!' }) }) app.listen(process.env.PORT || 3000) # npm start httpで3000ポートにアクセス →message "Hello world!"が表示される
リクエスト&レスポンスの動作確認
# cd ../frontend/ # npm install --save axios # cd src/ # mkdir api # touch api/index.js
axiosの設定をインスタンス化する
# vim api/index.js import axios from 'axios' export default () => { return axios.create({ baseURL: `http://node.home.local:3000/` }) } # vim api/methods.js import Api from './index' export default { testPosting () { const item = { text: 'Success!' } return Api().post('/test', item) } // 他の処理も追加可能 }
POST機能テストのためにfrontendのHTMLを修正
# vim frontend/src/components/HelloWorld.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <!-- ごちゃごちゃしていたのを全て消して、ボタンを配置 --> <button @click='post'>click me</button> </div> </template> <script> import Methods from '@/api/methods' export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, methods: { // サーバーから返ってくる値をログに出力したいのでasyncとawaitを行う async post() { let response = await Methods.testPosting() console.log(response) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
# vim backend/index.js app.get('/test', function(req, res) { res.send({ message: 'Hello world!' }) }) // 以下に書き換え app.post('/test', function(req, res) { res.send({ message: req.body.text }) }) httpの8080番にアクセスし、「click me」ボタンをクリック

→コンソールにSuccessが表示されました。
参考サイト
次回は、クイズテンプレートを表示するです。
コメント