Vue-cli3.x中使用Axios发送跨域请求的配置方法
安装axiosnpm i axios -s
main.js中引入
import axios from 'axios'//将axios挂载在Vue扩展上Vue.prototype.$http=axios//在其他地方使用只需使用 this.$http来代替axios;//配置baseUrlaxios.defaults.baseURL = '/api'
vue.config.js配置
在devServer中加入
proxy: {'/api': {target: 'http://localhost:8888/EasyPicker',//请求的目标地址的BaseURLchangeOrigin: true, //是否开启跨域pathRewrite: {'^/api': '' //规定请求地址以什么作为开头}}}
配置完成后如下
module.exports = {configureWebpack: {devServer: {proxy: {'/api': {target: 'http://localhost:8888/EasyPicker',changeOrigin: true, //是否跨域pathRewrite: {'^/api': '' //规定请求地址以什么作为开头}}}}}}
完成上述配置后差不多算大功告成了,下面是请求示例demo1: 如果我们要发送请求的路径为http://localhost:8888/EasyPicker/user/login配置完成后的请求方式为(关于axios更具体的用法请参照中文文档)
this.$http("/user/login",{username:"admin",password:"123456"})
控制台发送的请求截图显示的路径为 ↓http://localhost:8088/api/user/login实际请求路径为↓http://localhost:8888/EasyPicker/user/login
通过上述简单的配置即可完成跨域请求的发送,前后端分离开发中非常实用的技巧