本篇的难点就在于 egg-cors,用于解决跨域请求
Step 0. 基础不多说
使用egg快速初始化
$ npm i egg-init -g
$ egg-init egg-example --type=simple
$ cd egg-example
$ npm i
参考egg.js官方文档
Step 1. 安装 egg-cors
npm i egg-cors --save
在 /app/config/plugin.js 启用egg-cors
exports.cors = { enable: true, package: 'egg-cors',
};
Step 2. 允许相应的请求
// 允许请求
config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
}; config.security = { csrf: { enable: false, }
};
前端示例:(使用webpack)
(1)main.js的配置
!!! 前提先安装好 axios, 封装 axios 成为ajax工具,便于使用
import Vue from 'vue'
import App from './App'
import router from './router'
// 需要先安装好 axios
import Axios from 'axios'
const AXIOSBASE = Axios.create({
baseURL:'http://127.0.0.1:7001'
});
Vue.prototype.$api = AXIOSBASE;
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: ''
})
(2)login.vue的使用
学会了使用 async await
checkLogin: async function () {
let loginInfo = {
username: this.username,
password: this.password
}
let response = await this.$api.post('/login',loginInfo)
console.log(response)
嗯哼~
本篇就写这么多了,我的学习记录写完了
望能帮助到有需要的你~