步骤:
1、创建 vue.config.js 文件
2、在 vue.config.js 中配置 devServer
3、发送请求时,把远程服务器的域名端口改成本地域名、本地端口
vue-cli 3.x 以后的版本,不会在项目根目录生成 vue.config.js ,所以需要自己手动创建一个,以下是vue-cli官网的介绍:
创建 vue.config.js 文件:
修改此文件 需要重启vue项目才能生效
module.exports = {
// lintOnSave: false,
/**
* 代理服务器跨域请求 原理:
* 建立一个代理服务器 A ,端口与域名都与本地一致
* 代理服务器 A 收到本地请求,进而向远程服务器 B 转发请求,获取数据
* (服务器间的通信,是最原始的 http 通信,没有浏览器同源策略,所以不会有跨域问题)
* 代理服务器 A 向 服务器 B 请求到数据,返回本地。实现跨域请求。
*
* 代理服务器发送请求,会先访问本地服务器(vue-cli所在服务器)的 public 文件夹,
* 如果访问的数据 public 文件夹下有,会优先返回本地文件
*/
/**s
* 开启代理服务器 方式一: 简版
* 缺点:
* 请求的文件,如果本地有,会优先返回本地资源
* 只能配置一个代理服务器
*/
// devServer: {
// proxy: 'http://localhost:8888'
// }
/**
* 开启代理服务器 方式二:
*
* 可以开启多个代理服务器
*
* 可以自定义请求前缀,避免访问到本地服务器资源
*/
devServer: {
proxy: {
// 这里配置请求前缀 该代理服务器 使用前缀 /api 调用
'/api': {
// 目标服务器以及端口
target: 'http://localhost:8888',
// 代理服务器转发请求时,去除自定义的 api 字段
pathRewrite: { '^/api': '' },
// 用于配置支持 webSocket
ws: true,
// 用于配置请求头中的 host 字段 若为 true , 则字段为目标服务器的 地址+端口
changeOrigin: true
}
}
}
}
vue 组件:
<template>
<div class="contanier">
<button @click="getData">跨域请求数据(不带请求前缀)</button>
<br>
<br>
<button @click="getData1">跨域请求数据(带请求前缀)</button>
<br>
<br>
<button @click="getData3">不使用代理服务</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
}
},
// 请求的服务器以及端口,使用 vue-cli 本地运行的服务器端口,
// 符合同源策略,代理服务器负责转发请求获取数据
methods: {
// 请求方式一: 简版
getData(){
console.log('点击 不带请求前缀');
axios.get('http://localhost:8080/index').then( response => {
console.log(response);
})
},
// 请求方式二: 带请求前缀 api
getData1(){
console.log('点击 带请求前缀');
// 自定义请求前缀,放在 端口后面
axios.get('http://localhost:8080/api/index').then( response => {
console.log(response);
})
},
getData3(){
console.log('点击 不使用代理服务器');
// 不使用代理服务器,直接访问端口 8888
axios.get('http://localhost:8888/index').then( response => {
console.log(response);
})
},
}
</script>
<style scoped>
</style>