egg.js ajax上传文件,egg.js作为服务端接受post跨域请求(简单实现)

本篇的难点就在于 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)

嗯哼~

本篇就写这么多了,我的学习记录写完了

望能帮助到有需要的你~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值