express是node.js环境下的web服务端开发框架,特别适合个人网站的服务端开发。
这次实践的目的:网址导航的设计
具体的流程:用户发送http请求,服务端处理请求,查询MongoDB中保存的网址信息,将查到的信息发送给前端实现网页的渲染后响应用户的请求。
1 . 首先下载安装node.js、MongoDB,到官网下载最新软件安装包,直接安装即可。
完成后安装Vue,参考 Vue问题解决方法收录 中的vue安装入门。
开发工具选择HBuilderX搭配NotePad++,官网下载安装即可。
2 . express上手:目前实现express从MongoDB中查询数据,然后前端使用vue框架来显示查询到的数据,中间的通信使用axios。
新建一个文件夹webserver,然后在这个目录下执行 npm install --save express 完成后按照下图新建各个js文件
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5iNmljM1I2MxMzNzUjYmNGNycjY2YzNxQjYkBjMkFzYh9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
app.js文件中输入:
const express = require('express')
const route = require('./routes/index.js')
const app = express()
// 注册路由处理函数
route(app)
// 服务端监听
app.listen(3000 , function(){
console.log('Server start listen at : ' + String(3000))
})
index.js 文件中输入:
const website = require('./website.js')
module.exports = (app) => {
app.use(website)
}
website.js文件中输入:
const express = require('express')
const router = express.Router()
//路由事件响应函数
router.get('/api/website', (req,res) =>{
res.status(200).send("Get website Success!")
})
module.exports = router
浏览器中输入:http://localhost:3000/api/website 显示Get website Success!
以上完成服务端的基本结构设计。
接下来加入MongoDB操作的代码,实现从MongoDB中读取数据并返回给浏览器
安装 mongoose库: npm install mongoose --save 完成后,按如下修改代码
db.js文件中输入:
const mongoose =require('mongoose')
const Schema = mongoose.Schema
//创建数据集
const WebSiteSchema = new Schema(
{
webtype: String,
name: String,
url: String,
title: String,
meta: String,
metatype: String,
value: Number
},
{
versionKey: false
}
)
//数据集与数据库中的数据集合绑定
const Models = {
WebSite: mongoose.model('website',WebSiteSchema,'websites')
}
//连接打开数据库
mongoose.connect('mongodb://127.0.0.1/my-blog')
const db = mongoose.connection
db.on('error', console.error.bind(console,'Database connnection error.'));
db.once('open',() => {
console.log('The Database has connected.')
});
module.exports = Models
website.js文件修改
// 引入数据库操作模块
const db = require('../db/db.js')
router.get('/api/website', (req,res) =>{
db.WebSite.findOne({},(err,doc) =>{
if(err){
console.log(err)
}else {
//返回查到的结果
res.status(200).send(doc)
}
})
})
最终浏览器访问结果:
3 . 我们使用vue框架来构建我们的前端显示页面,显示前面我们从服务端获取的json格式的数据。
按照步骤1中的提示建立一个vue的前端工程webexample
之后安装axios :npm install axios --save 完成后按照下面修改对应文件
修改HelloWord.vue位website.vue, 代码修改如下:
<template>
<div class="hello">
<div class = "a">{{name}}</div>
<div class = "b">{{url}}</div>
<div class = "c">{{meta}}</div>
</div>
</template>
<script>
export default {
data () {
return {
url : 'baidu',
name: '百度',
meta : '搜索',
msg: '',
}
},
methods:{
GetWebSite(){
let that = this;
this.$http.get('/api/website').then(function(res){
console.log(res.data);
that.url = res.data.url;
that.name = res.data.name;
that.meta = res.data.meta;
}).catch(function(err){
console.log(err);
});
},
},
created(){
this.GetWebSite()
}
}
</script>
<style scoped>
</style>
index.js文件修改如下:
import Vue from 'vue'
import Router from 'vue-router'
import WebSite from '@/components/website'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'WebSite',
component: WebSite
}
]
})
main.js加入如下代码:
import axios from 'axios'
Vue.prototype.$http = axios //引入axios
config\index.js的加入跨域的设置:
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
}, //跨域转发
浏览器访问结果
代码下载链接:http://pan.foxhost.top,提取码:2696