什么是跨域
跨域问题的出现是因为浏览器的同源策略问题,所谓同源:就是两个页面具有相同的协议(protocol),主机(host)和端口号(port),它是浏览器最核心也是最基本的功能,如果没有同源策略我们的浏览器将会十分的不安全,随时都可能受到攻击。
跨域的表现
打开浏览器控制台(F12),当我们请求一个接口的时候,出现如:Access-Control-Allow-Origin 字眼的时候说明请求跨域了。
具体报错信息为No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8080’ is therefore not allowed access. The response had HTTP status code 403
解决跨域
当前环境
1、vue-cli ----> 3.0
2、nodejs ----> v12.15.0
3、vuejs ----> 2.6
步骤
一、在vue.config.js文件下
proxy: {
'/guoguo': {
/*changeOrigin为true表示开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题*/
changeOrigin: true,
/*
target为真正要访问的接口地址
*/
target: `http://116.33.22.11`,
ws: true, // 是否启用websocket
},
}
二、axios请求文件下
import axios from "axios";
const service = axios.create({
//这里的baseURL和步骤一里的'/guoguo'是对应起来
baseURL: "/guoguo",
timeout: 50000
});
三、api文件下
export function queryUserPageList(data) {
/*
如果proxy代理成功,那么这里表示的真正的接口地址为http://116.33.22.11/guoguo/userManage/xxx
*/
return request({
url: '/userManage/xxx',
method: 'get',
params:data
})
}