打开Config --> index.js文件
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': { // 匹配所有以 '/api'开头的请求路径
target: 'http://127.0.0.1:8000', // 代理目标的基础路径
changeOrigin: true, // 支持跨域
// secure: false, // 如果是https接口,需要配置这个参数
pathRewrite: {// 重写路径: 去掉路径中开头的'/api'
'^/api': ''
}
}
},
api -->ajax.js文件
/*
ajax请求函数模块
返回值: promise对象(异步返回的数据是: response.data)
*/
import axios from 'axios'
export default function ajax (url, data={}, type='GET') {
url="/api"+url ///api是Config --> index.js文件里配置的路径
return new Promise(function (resolve, reject) {
// 执行异步ajax请求
let promise
if (type === 'GET') {
// 准备url query参数数据
let dataStr = '' //数据拼接字符串
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&'
})
if (dataStr !== '') {
dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
url = url + '?' + dataStr
}
// 发送get请求
promise = axios.get(url)
} else {
// 发送post请求
promise = axios.post(url, data)
}
promise.then(function (response) {
// 成功了调用resolve()
resolve(response.data)
}).catch(function (error) {
//失败了调用reject()
reject(error)
})
})
}
/*
const response = await ajax()
const result = response.data
const resule = await ajax()
*/
1 vue前端结局跨域主要思想是代理功能,比如:
vue项目:http://localhost:8080/
后端项目:http://127.0.0.1:8000/
2.在浏览器端访问 http://localhost:8080/api/index/ 路径时,vue会匹配到以 /api/ 开头的请求
3.此时 vue会使用代理功能 自动转发到 http://127.0.0.1:8000/index/ 此时就是同一个域,就不会触发跨域问题