The following Vue.js tutorial column will introduce to you how to use vue-cli combined with express to obtain data in mongodb. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
I have been reading about node recently. I made a small crawler in my free time to crawl the data of Movie Paradise and write it into mongodb. Code address : https://github.com/fangming666/dianyingtiantang/blob/master/nodeServer/index.js
Then the mongodb data obtained is as follows:
We only need to get the data in data. So, how do we get it? My idea is to use node's express in vue-cli, and then query the database. After my exploration, this way is possible;
First, we need to install mongodb and express:
cnpm install mongodb express --save-dev
Then I need to set it up in webpack.dev.confis.js. The file path is as follows:
Okay, let’s start our code journey:
1. Configure express:
//配置express服务器 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);
2. Query the data in mongodb:
let MongoClient = require('mongodb').MongoClient; let DB_CONN_STR = 'mongodb://localhost:27017/test'; let dataS = {}; let movie = () => { let selectData = function (db, callback) { //连接数据库 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; };
Those who don’t understand the syntax can go here Take a look at the mongodb syntax of node in the novice tutorial. Without going into details, just Baidu it yourself;
3. Find the devServer and add:
before(app){ app.get("/api/giveData", (req, res) => { res.json({ errno: 0, data: movie().data }) }); }
This What is written in devServer, this is written in devServer, this is written in devServer, important things should be said three times.
4. Re-execute cnpm run dev and enter: http://localhost:8080/api/giveData/ in the browser:
When we use it, we only need to write the interface address as "http://localhost:8080/api/giveData/" to access the data
Related recommendations:
2020 Summary of front-end vue interview questions (with answers)
vue tutorial recommendation: 2020 latest 5 vue.js video tutorial selections
For more programming-related knowledge, please visit: Programming Courses! !
The above is the detailed content of Introduction to the method of obtaining mongodb data with vue-cli+express. For more information, please follow other related articles on the PHP Chinese website!