一.使用express搭建一个临时服务器
npm init -w
创建一个package.json public文件夹作为静态文件存放index.html
npm i express -S
二.创建一个index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Async/await</title>
<!-- CDN 引入vue 和 axios -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<!-- 输入框区域 -->
<div style="height:50px">
<input type="text" placeholder="请输入电话号码" v-model="phoneNum">
<button @click="getFaceResult">确定</button>
</div>
<!-- 充值面值 显示区域 -->
<div>
充值面值:
<span v-for="item in faceList" :key='item'>
{{item}}
</span>
</div>
</div>
<!-- js 代码区域 -->
<script>
new Vue({
el: '#app',
data: {
phoneNum: '12345',
// faceList: ["20元", "30元", "50元"],
faceList: []
},
methods: {
//获取到城市信息
getLocation(phoneNum) {
return axios.post('phoneLocation', {
phoneNum
})
},
// 获取面值
getFaceList(province, city) {
return axios.post('/faceLists', {
province,
city
})
},
//确定按钮
async getFaceResult() {
// this.getLocation(this.phoneNum).then(res=>{
// if(res.status === 200 && res.data.success){
// let province = res.data.obj.province;
// let city = res.data.obj.city;
// this.getFaceList(province,city)
// .then(res=>{
// if(res.status === 200 && res.data.success){
// this.faceList = res.data.obj;
// }
// })
// }
// }
// ).catch(err =>{
// console.log(err);
// })
let location = await this.getLocation(this.phoneNum);
console.log(location);
if(location.data.success){
let province = location.data.obj.province;
let city = location.data.obj.city;
let faceMoney = await this.getFaceList(province,city);
console.log(faceMoney);
this.faceList = faceMoney.data.obj;
}
}
}
})
</script>
</body>
</html>
三. 新建一个server.js文件
server.js文件中的内容
const express = require('express');
const app = express();
app.use(express.static('public'));
// 电话号码返回省和市,为了模拟延迟,使用了setTimeout
app.post('/phoneLocation', (req, res) => {
setTimeout(() => {
res.json({
success: true,
obj: {
province: '广东',
city: '深圳'
}
})
}, 1000);
})
// 返回面值列表
app.post('/faceLists', (req, res) => {
setTimeout(() => {
res.json(
{
success: true,
obj:['10元','20元', '30元', '50元', '100元']
}
)
}, 1000);
})
app.listen(3000, ()=>{
console.log('server start');
})
在页面中输入http://localhost:3000 即可看到内容
//服务启动命令 nodemon server