前端代码
<template>
<div id="app">
<input type="text" v-model="myname">
<button @click="check()">检测用户名是否存在</button>
<span>{{info}}</span>
</div>
</template><script>
export default {
name: 'App',
data() {
return {
myname: '',
info: ''
}
},
methods: {
check() {
// 访问后端服务器
// this.axios({
// // 访问后端服务器的方法
// method: 'get',
// url:'http://localhost:8000/users',
// // mydata就是保存服务器返回的用户信息的变量
// })
// 以上axios调用代码等价于:
this.axios.get('http://localhost:8000/users')
.then((mydata)=>{
// console.log(mydata)
console.log(mydata.data)
// 标识变量的作用是表示程序的运行状态
let flag = false //true表示用户名已经存在的状态,false表示用户名不存在的状态
for(let i=0;i<mydata.data.length;i++) {
//如果输入的用户名已经存在于用户列表中
if(this.myname == mydata.data[i].username){
flag = true
}
}
if(flag==true) {
// alert('用户名已存在!')
this.info = '用户名已存在!'
}
else {
// alert('用户不存在!')
this.info = '用户名不已存在!'
}
})
}
}
}
</script><style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
后端代码
// 导入express框架,然后将该框架保存到变量express中
// commonJS规范
const express = require('express')
// 导入允许前端程序访问后端服务器的插件cors
const cors = require('cors')
// const mysql = require('mysql')// 创建后端服务器
const myserver = express()// 调用cors插件,运行
myserver.use(cors())// 创建/users后端路由,此类路由的特点是:一个路由路径对应于一个函数,当前端程序访问这个路由路径的时候,就会调用该函数对前端进行响应
myserver.get('/users',function(request,response){
// request代表前端发送给后端的请求数据,它是一个对象{...}
// response代表后端要向前端发送的响应数据,它也是一个对象{...}
// response.json(要发送给前端的JSON数据)
let userlist = [
{username:'tom',pwd:123},
{username: '李芳',pwd:456},
{username: 'jack',pwd:789}
]
response.json(userlist)
})// 启动服务器
myserver.listen(8000,function(){
console.log('服务器启动成功!')
})