新聞中心
這篇文章將為大家詳細講解有關(guān)vue-cli+express如何獲取mongodb數(shù)據(jù),小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

最近一直在看node有關(guān)的內(nèi)容,空閑時間做了一個小小的爬蟲,用于爬取電影天堂的數(shù)據(jù)然后寫到mongodb里面,代碼地址:https://github.com/fangming666/dianyingtiantang/blob/master/nodeServer/index.js
然后獲取的mongodb數(shù)據(jù)如下:

我們只需要得到data里面的數(shù)據(jù)就可以了。那么,我們怎么去得到呢,我的想法是,在vue-cli里面使用node的express,然后再執(zhí)行查詢數(shù)據(jù)庫的操作即可,經(jīng)過我的探索,這條路是可以的;
首先,我們需要安裝mongodb和express:
cnpm install mongodb express --save-dev
然后我需要在webpack.dev.confis.js里面進行設(shè)置,文件路徑如下:

好嘞,開始我們的代碼征程:
一、配置express:
//配置express服務(wù)器
let express = require("express");
let apiServer = express();
let bodyParser = require("body-parser");
apiServer.use(bodyParser.urlencoded({extended: true}));
apiServer.use(bodyParser.json());
let apiRouter = express.Router(); //配置路由
apiServer.use("/api", apiRouter);二、查詢mongodb里面的數(shù)據(jù):
let MongoClient = require('mongodb').MongoClient;
let DB_CONN_STR = 'mongodb://localhost:27017/test';
let dataS = {};
let movie = () => {
let selectData = function (db, callback) {
//連接數(shù)據(jù)庫
let dbS = db.db("test");
//連接到表
let collection = dbS.collection('dytt');
collection.find({}).toArray(function (err, result) {
if (err) {
console.log('Error:' + err);
return;
}
callback(result);
});
};
MongoClient.connect(DB_CONN_STR, function (err, db) {
console.log("連接成功!");
selectData(db, function (result) {
db.close();
console.log(result[0]);
dataS = result[0];
});
});
return dataS;
};這里不懂語法的可以去看一下菜鳥教程的node這一塊mongodb 的語法,不贅述,自行百度即可;
三、找到devServer,在里面添加:
before(app){
app.get("/api/giveData", (req, res) => {
res.json({
errno: 0,
data: movie().data
})
});
}這是寫在devServer里面的,這是寫在devServer里面的,這是寫在devServer里面的,重要的事情說三遍。
四、重新執(zhí)行cnpm run dev,在瀏覽器中輸入:http://localhost:8080/api/giveData/即可:

我們使用的時候只需吧接口地址寫成“http://localhost:8080/api/giveData/”就可以去訪問數(shù)據(jù)了
關(guān)于“vue-cli+express如何獲取mongodb數(shù)據(jù)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
分享標(biāo)題:vue-cli+express如何獲取mongodb數(shù)據(jù)-創(chuàng)新互聯(lián)
標(biāo)題來源:http://www.dlmjj.cn/article/dcsesj.html


咨詢
建站咨詢
