Vue进行前后端交互

前端代码


<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('服务器启动成功!')
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值