axios
请求接口├── @vue/cli@4.1.2css
├── @vue/cli-init@4.1.2前端
vue init webpack ./
// 先切换到/client
目录下npm i -S axios
// 先切换到/client
目录下npm run start
查看页面是否能正常访问localhost:8080
本身的项目,没特殊要求,选择本身熟悉的element-ui
UI库、scss
预编译语言快速搭建页面。vue
// 更新文件:/client/src/App.vue <template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'App' } </script>
// 更新文件:/client/src/router/index.js // 顺便删除文件:/client/src/components/Helloworld.vue import Vue from 'vue' import Router from 'vue-router' import Login from '@/views/login' Vue.use(Router) export default new Router({ routes: [ { path: '/', redirect: '/login' }, { path: '/login', name: 'login', component: Login } ] })
// 新建文件: /client/src/views/login/index.vue <template> <div> Login </div> </template>
展现效果 //更新不及时,能够重启前端服务node
element-ui
和scss
npm i -S element-ui node-scss sass-loader@7
// sass-loader安装7.版本,目前最新版8.编译失败// 更新文件:/client/src/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 ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import App from './App' import router from './router' Vue.config.productionTip = false Vue.use(ElementUI) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
// 更新文件:/client/src/views/login/index.vue <template> <div> <el-button type="primary">Login</el-button> <p class="red">这是scss</p> </div> </template> <style lang="scss" scoped> $color: red; .red { color: $color; } </style>
为了省事,直接从Element
官网 > 组件 > Form表单,拷贝一份带校验的示例改改webpack
// 更新文件:/client/src/views/login/index.vue <template> <div class="page-login"> <el-form :ref="formName" class="form-login" :model="form" :rules="rules"> <el-form-item label="账号" prop="account"> <el-input v-model="form.account" placeholder="请输出账号"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="form.password" placeholder="请输出密码"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onLogin">登录</el-button> <el-button type="primary" @click="onRegister">注册</el-button> </el-form-item> </el-form> </div> </template> <script> export default { name: 'Login', data () { return { formName: 'LoginForm', form: { account: '', password: '' }, rules: { account: [ { required: true, message: '请输入账号', trigger: 'blur' }, { min: 5, message: '长度至少5个字符', trigger: 'blur' } ], password: [ { required: true, message: '请输入密码', trigger: 'blur' }, { min: 3, message: '长度至少3个字符', trigger: 'blur' } ] } } }, methods: { async onLogin () { console.log('login') }, async onRegister () { console.log('register') } } } </script> <style lang="scss" scoped> @import './index.scss'; </style>
// 新建文件:client/src/views/login/index.scss .form-login { width: 600px; margin: 0 auto; }
在准备工做时,已经npm i -S axios
安装axios
。ios
// 新建配置文件:client/src/config/http.js export const BASE_URL = 'http://localhost:3000/' export const TIMEOUT = 15000
// 新建axios实例文件:client/src/utils/http.js import axios from 'axios' import { BASE_URL, TIMEOUT } from '@/config/http' const instance = axios.create({ baseURL: BASE_URL, timeout: TIMEOUT, validateStatus: function (status) { // return status >= 200 && status < 300; // default return status >= 200 // 可拦截状态码>=200的请求响应 } }) export default instance
注意:axios默认只返回Http Code为2**
请求的响应nginx
//更新文件:server/control/users.js async function list (ctx) { try { const users = await userModel.find(); //查出所有用户 ctx.body = { code: '200', data: users, msg: '查询成功' } } catch (err) { ctx.body = { code: '403', data: null, msg: err.message } } }
//更新文件:client/src/views/login/index.vue ... <script> import http from '@/utils/http' ... methods: { async onLogin () { console.log('register') }, async onRegister () { console.log('register') } }, async created () { const res = await http.get('/users') console.log(res) } ... </script> ...
发生跨域请求,这里咱们切换到/server/
目录下,安装依赖npm i -S koa2-cors
(线上的话,可使用nginx
作代理)git
// 更新文件:server/app.js const koa = require('koa'); const bodyParser = require('koa-body'); const cors = require('koa2-cors'); const routes = require('./router'); const app = new koa(); app.use(cors()); ...
重启后端服务,便可在页面http://localhost:8080/#/login
看到请求结果github
从返回接口能够看出,请求服务端成功时,只须要res.data
便可,使用instance.interceptors
对返回数据进行过滤。web
// 更新文件:client/src/utils/http.js ... // Add a response interceptor instance.interceptors.response.use( async res => { if (/^20./.test(res.status)) { return res.data } console.log('------response=======', res) return res }, error => { return Promise.reject(error) } ) export default instance
请求结果
//更新文件:client/src/views/login/index.vue ... async onLogin () { try { const valid = await this.$refs[this.formName].validate() if (valid) { const { account, password } = this.form const res = await http.post( '/users?action=login', { account, password, } ) console.log(res) if (res && res.code === '200') { this.$router.replace('/home') } else { this.$message({ // 没有使用this.$message.error('') type: 'error', message: res.msg }) } } } catch (err) { console.error(err) } }, ...
this.$message({})
,而没有使用this.$message.error()
,由于发现若是res没有返回的话,会报Element
的错误,形成信息误导。更新路由文件,使登陆成功跳转到Home
组件
// 更新路由文件: import Vue from 'vue' import Router from 'vue-router' import Login from '@/views/login' import Home from '@/views/home' Vue.use(Router) export default new Router({ routes: [ { path: '/', redirect: '/login' }, { path: '/login', name: 'login', component: Login }, { path: '/home', name: 'home', component: Home } ] })
// 新建文件:client/src/views/home/index.vue <template> <div>Home</div> </template>
使用上节经过Postman
建立的admin
帐户登陆,结果展现
缓慢的动图以下:
//更新文件:client/src/views/login/index.vue ... async onRegister () { try { const valid = await this.$refs[this.formName].validate() if (valid) { const { account, password } = this.form const res = await http.post( '/users?action=register', { account, password } ) if (res.code === '200') { this.$refs[this.formName].resetFields() this.$message({ type: 'success', message: '注册成功' }) } else { this.$message({ type: 'error', message: res.msg }) } } } catch (err) { console.error(err) } } ...
测试失败结果
测试成功结果
可使用新建立的账号登陆,发现能够成功/查看数据库,是否成功新增用户