改造Express
生成的初始項(xiàng)目結(jié)構(gòu),使其符合目前使用的規(guī)范渴邦,并且進(jìn)一步code
走触,能夠出示一個(gè)簡(jiǎn)單的demo
,本地的前端工程和后端工程能夠完成通信,前端成功展示后端返回的數(shù)據(jù)习勤。
目錄結(jié)構(gòu)的變化
Express
自動(dòng)創(chuàng)建的server
項(xiàng)目代碼結(jié)構(gòu)如下:
這個(gè)初始化的目錄結(jié)構(gòu)相對(duì)比較復(fù)雜一點(diǎn)踪栋,而我們?cè)谑褂玫臅r(shí)候有些目錄是不需要的(每個(gè)人根據(jù)實(shí)際的需要進(jìn)行定制化),這里我只需要極簡(jiǎn)的框架結(jié)構(gòu)图毕,易于理解并可以使用即可夷都,變化后的接口框架如下:
調(diào)整過后的目錄結(jié)構(gòu)十分簡(jiǎn)潔,一個(gè)請(qǐng)求過來之后予颤,基本的傳播路徑為:
當(dāng)然上面給的傳播路徑是期望如此的囤官,但是有的時(shí)候,編碼人員在一開始沒有規(guī)范好就會(huì)導(dǎo)致關(guān)系有錯(cuò)亂蛤虐,個(gè)人覺得這樣會(huì)比較清晰(有其他好的可以交流一下哦!)
Demo
源碼實(shí)現(xiàn)
這里只是實(shí)現(xiàn)了一個(gè)最簡(jiǎn)單的GET
請(qǐng)求由前端發(fā)起党饮,后端響應(yīng),最后前端展示的demo
驳庭,雖然簡(jiǎn)單刑顺,但是基本能夠與上面的請(qǐng)求傳播路徑相互對(duì)齊。
server
端源碼
//app.js
const msgInfo = require('./interfaces/i-msgInfo');
app.use('/msgInfo', msgInfo);
//i-msgInfo.js
const express = require('express');
const router = express.Router();
const msgDao = require('../services/msgInfo');
const msgInfo = async(req,res)=>{
try {
let msgInfo = await msgDao.getMsgInfo();
res.send(msgInfo);
} catch (err) {
res.send(err)
}
}
router.get('/', msgInfo);
module.exports = router;
//msgInfo.js
const common = require('../utils/common');
const msgInfo = {};
msgInfo.getMsgInfo = async () => {
try {
let msgInfo = 'Welcome to Your Vue&Express App';
return msgInfo;
} catch (err) {
throw {
code: common.SERVICEERRCODE,
msg: err.msg || JSON.stringify(err)
}
}
}
module.exports = msgInfo;
//common.js
const common = {};
common.SERVICEERRCODE = 3;
module.exports = common;
最核心的代碼都在上面貼了出來饲常,彼此之間的關(guān)系也十分的明確蹲堂,建議動(dòng)手操作一波。
View
端源碼
在前端代碼中不皆,主要改造的是安裝異步請(qǐng)求的包axios
贯城,并在HelloWorld
中發(fā)起GET
請(qǐng)求,將請(qǐng)求的結(jié)果展示在首頁(yè)上霹娄,還需要注意的是跨域的問題能犯。
//main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
beforeCreate () {
window.util = {}
window.util.$http = axios.create({
timeout: 1000 * 50,
withCredentials: true
})
}
})
//HelloWorld.vue
export default {
name: 'HelloWorld',
data () {
return {
msg: ''
}
},
created () {
//在created中data已經(jīng)初始化完畢,所以可以在這里進(jìn)行賦值
this.msg = this.getMsg()
},
methods: {
//Get請(qǐng)求犬耻,并將結(jié)果賦值給data中的msg
getMsg: function () {
window.util.$http.get('/api/chai/agent/msgInfo').then(r => {
this.msg = r.data
})
}
}
}
//config/index.js
//這里主要就是解決本地跨域的問題踩晶,在測(cè)試環(huán)境或者生產(chǎn)環(huán)境可以利用其它手段解決跨域
proxyTable: {
'/api/chai/agent': {
target: 'http://127.0.0.1:9106/',
changeOrigin: true,
pathRewrite: {
'^/api/chai/agent': ''
}
}
}
Demo
最終結(jié)果
最終由上圖所示,server
返回的結(jié)果枕磁,正確的在前端頁(yè)面上面展示渡蜻。