Vue.js(Vue-CLI 3) + express + mogoDB 設置編 SPA開発(19) #Vue.js #node,js #mongoDB #javascript #web #SPA
index:
概要:
SPA (Vue.js/ Vuec CLI 3) 関連で、
express(node.js) , mogoDBの組合せになります。
vue-cli-plugin-express プラグインで、express追加しています。
環境
vue.js
Vue-CLI 3
mongodb-4.0.10
express 4.16.1
node.js
npm
設定方法
Vue CLI3に、express追加
vue add express
・Should serve vue app
=> Y にしました。
・ npm run express で、express 起動
実装など
app.get('/api_test1', function(req, res) { var collection = db.get('books'); collection.find({},{},function(e,docs){ //console.log("#doc"); var param = {"docs": docs }; res.json(param); }); }); // app.post('/api_post1', (req, res) => { console.log(req.body.title ) var obj = req.body; var collection = db.get('books'); collection.insert(obj , function(err, result ) { if (err) throw err; res.json(req.body); db.close(); }); });
Vueコンポーネント
・send_post()で、レコード追加しています。
<template> <div class="hello"> <h1>{{ msg }}</h1> <hr /> <div class="form-group"> <label for="TopicTitle">タイトル</label> <input type="text" class="form-control" id="title" v-model="title"> </div> <div class="form-group"> <label for="TopicContent">content</label> <textarea class="form-control" id="content" rows="3" v-model="content"></textarea> </div> <button v-on:click="send_post">投稿</button> </div> </template> <script> import axios from 'axios' export default { name: 'HelloWorld', data () { return { message : 'msg-123', msg : "", title : "", content : "", } }, created () { this.get_foo() }, methods: { get_foo () { axios.get("/api_test1") .then(res => { var items = res.data.docs console.log(items) items.forEach( function (item) { console.log(item) }); // this.msg = res.data.msg }) }, send_post(){ var task = { 'title': this.title, 'content': this.content }; axios.post('/api_post1' , task ).then(res => { console.log(res.data ); // console.log(res.data.content); }); }, } } </script>