Vue+Node服務(wù)器查詢Mongo數(shù)據(jù)庫及頁面數(shù)據(jù)傳遞操作實例分析
本文實例講述了Vue+Node服務(wù)器查詢Mongo數(shù)據(jù)庫及頁面數(shù)據(jù)傳遞操作。分享給大家供大家參考,具體如下:
1、利用Mongoose查詢MongoDB
通過mongoose依賴可以簡捷地操作mondodb數(shù)據(jù)庫,首先安裝mongoose:
cnpm install mongoose --save
使用mongoose需要一個模式Schema,它用于定義你從mongodb中查詢的每個文檔條目的內(nèi)容,然后通過mongoose.model()生成一個模板model,模板像一個架子,將數(shù)據(jù)庫取到的每個條目中的內(nèi)容按架子的結(jié)構(gòu)填充,這樣就形成了一個便于操作、結(jié)構(gòu)條理的數(shù)據(jù)對象。通過這個對象就可以訪問模板的相關(guān)屬性,甚至為其定義函數(shù)方法。
例如mongodb中的數(shù)據(jù)庫mall中的商品條目如圖:

(PHP Storm中有簡單的mongo可視化插件。通過搜索mongo plugin安裝該插件,之后在phpstorm主菜單的view/Tool Windows中找到mongo explore開啟mongo側(cè)邊欄工具,并連接到mongo數(shù)據(jù)庫后就能可視化查看其中數(shù)據(jù))
針對其定義Schema,生成并導出商品模板goods:
//在服務(wù)端server/modules文件夾下新建goods.js文件
const mongoose=require('mongoose');
let Schema=mongoose.Schema;
let productSchema=new Schema({ //通過mongoose的Schema定義模板
"productId":String,
"productName":String,
"salePrice":Number,
"productImage":String
});
//導出模板goods
module.exports=mongoose.model('goods',productSchema);
注意:Schema中字段的名稱要與數(shù)據(jù)庫中一致,否則會因為字段不匹配而造成無法操作數(shù)據(jù)庫。例如我在數(shù)據(jù)庫中是productImage,而schema中是productImg,導致插入時丟失字段。
然后通過goods模板執(zhí)行數(shù)據(jù)庫查詢操作,如果有錯返回err,否則返回查詢結(jié)果doc:
goods.find({},(err,doc)=>{callback()});
2、Node服務(wù)端查詢數(shù)據(jù)庫并返回結(jié)果
①、通過Express框架進行數(shù)據(jù)庫連接:
//服務(wù)端server/routes/goods.js文件
//引入相關(guān)模塊
const express=require('express');
const router=express.Router();
const mongoose=require('mongoose');
const goods=require('../modules/goods') //引入goods模板
//連接本地mongodb數(shù)據(jù)庫的mall集合
mongoose.connect('mongodb://localhost:27017/mall');
mongoose.connection.on('connected',()=>{
console.log("mongoDB連接成功");
});
mongoose.connection.on('erroe',()=>{
console.log("mongoDB連接出錯");
});
mongoose.connection.on('disconnected',()=>{
console.log("mongoDB斷開連接");
});
②、對來自前端的get請求進行響應(yīng):查詢數(shù)據(jù)庫mall集合并將結(jié)果放在result.list中,再加上status、msg,以json形式返回res。
router.get('/',(req,res,next)=>{
//利用goods模板調(diào)用mongooseAPI進行數(shù)據(jù)庫查詢
goods.find({},(err,doc)=>{ //查詢的回調(diào)函數(shù)
"use strict";
if (err){
res.json({
status:1,
msg:err.message
})
}else {
res.json({//利用res將數(shù)據(jù)返回給get請求
status:0,
msg:'',
result:{
count:doc.length,
list:doc
}
})
}
})
});
最后記得暴露路由router
module.exports = router;
注:接收請求中的參數(shù)一般有三種方式,
- req.query多用于get請求發(fā)送來的數(shù)據(jù),參數(shù)以?加在請求路徑的尾部,用req.query.keyname可以獲取到其中的數(shù)據(jù)。
- req.body用于接收post請求,post請求將數(shù)據(jù)放在request正文中,因此req.body.keyname可以得到其請求數(shù)據(jù)。
- req.params的參數(shù)包含在路徑當中,例如請求路徑為http://localhost:3000/test/myparam,在服務(wù)端讀取其中的參數(shù);
router.get('/testparams/:param', function (req, res) {
console.log('參數(shù)為: ' + req.params.param); //控制臺輸出路徑中的參數(shù):myparam
})
3、跨域請求數(shù)據(jù)
由于本地Vue運行在localhost:8080,而Node在localhost:3000,若要在vue中利用axios實現(xiàn)數(shù)據(jù)請求,則需要執(zhí)行跨域代理操作。在vue中的config/index.js文件的dev中配置一個轉(zhuǎn)發(fā)代理,當請求"/goods"時,轉(zhuǎn)發(fā)到localhost:3000下的/goods:

Node服務(wù)器對get請求的解析過程:當請求到達localhost:3000端時,Node服務(wù)器的app.js文件對請求路徑進行解析,通過app.use()將/goods定位到routes/goods.js文件,在該文件中查詢數(shù)據(jù)庫的操作并返回結(jié)果:
var goods=require('./routes/goods'); //包含文件routes/goods.js
app.use('/goods',goods); //將訪問路徑定位到文件
4、vue進行數(shù)據(jù)請求并渲染到頁面
在views/GoodsList.vue文件中利用axios對數(shù)據(jù)進行請求,定義getGoodsList()方法并在掛載后調(diào)用:
mounted:function (){
this.getGoodsList();
},
methods:{
getGoodsList(){
axios.get("/goods").then(response =>{
let res=response.data;
if(res.status==0){
this.goodsList=res.result.list;
}else{
console.log("從服務(wù)器請求數(shù)據(jù)失??!");
}
})
},
通過axios的get請求/goods,由于上面做了跨域代理,可以向Node服務(wù)端發(fā)送請求,在回調(diào)函數(shù)中,response的data是響應(yīng)返回的實際內(nèi)容,我們在服務(wù)端定義了返回狀態(tài)status,為0代表正常,并且將數(shù)據(jù)放在了result.list中,在頁面中對list數(shù)組進行遍歷即可將數(shù)據(jù)渲染到頁面:
注意在遍歷每個數(shù)據(jù)對象時,其鍵名要與在mongoDB中的定義一致,如item.salePrice可以訪問到條目的價格
<li v-for="(item,index) in goodsList">
<div class="pic">
<a href="#" rel="external nofollow" ><img v-lazy="`static/${item.productImage}`" alt=""></a>
</div>
<div class="main">
<div class="name">{{item.productName}}</div>
<div class="price">{{item.salePrice}}</div>
<div class="btn-area">
<a href="javascript:;" rel="external nofollow" class="btn btn--m">加入購物車</a>
</div>
</div>
</li>
啟動mongoDB、Node服務(wù)端、運行vue-cli框架后即可在localhost:8080內(nèi)看到結(jié)果如圖:

希望本文所述對大家node.js程序設(shè)計有所幫助。
相關(guān)文章
nodejs+websocket實時聊天系統(tǒng)改進版
這篇文章主要介紹了nodejs+websocket實時聊天系統(tǒng)的改進版,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
用nodejs實現(xiàn)json和jsonp服務(wù)的方法
本篇文章主要介紹了用nodejs實現(xiàn)json和jsonp服務(wù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
Node.js中使用mongoskin操作mongoDB實例
這篇文章主要介紹了Node.js中使用mongoskin操作mongoDB實例,Mongous是一個輕量級的nodejs mongodb驅(qū)動,需要的朋友可以參考下2014-09-09
nodejs實現(xiàn)一個自定義的require方法的詳細流程
大家對nodejs中的require方法應(yīng)該不會陌生,這個方法可以用來導入nodejs的內(nèi)置模塊,自定義模塊,第三方模塊等,使用頻率非常高,那么這個方法內(nèi)部是如何實現(xiàn)的呢?本篇文章就是從頭到尾拆分實現(xiàn)流程,最終實現(xiàn)一個自定義的require方法,需要的朋友可以參考下2025-03-03
Linux CentOS系統(tǒng)下安裝node.js與express的方法
這篇文章主要給大家介紹了在Linux CentOS系統(tǒng)下安裝node.js與express的方法,文中介紹的非常詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04

