一、了解跨域
1.同源策略
首先要了解什么是同源策略,
它是浏览器最核心也最基本的安全功能,现在所有支持JavaScript的浏览器都会使用这个策略。
同源是指,协议,端口号,域名相同。
非同源即是跨域了。
跨域时浏览器会报以下错误:
image.png
Access to XMLHttpRequest at 'http://m.kugou.com/rank/info/?rankid=23784&page=1&json=true' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
二、解决方法主要有2种:
image.png
1、后台解决,配置cors(Cross Origin Resource Sharing 跨域资源共享)
Java后台在spring-mvc.xml文件里面配置一下,支持一切请求跨域。
<!-- 跨域支持 -->
<mvc:cors>
<mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET,POST,OPTIONS"/>
</mvc:cors>
2、前端解决
开发的时候用proxy
image.png
proxyTable: {
'/api': {
// 测试环境
target: 'http://m.kugou.com/', // 接口域名
// secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, // 是否跨域,如果为true,请求的header将会设置为匹配目标服务的规则(Access-Control-Allow-Origin)
pathRewrite: {
'^/api': '/' //里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://m.kugou.com/rank/info/?rankid=23784&page=1&json=true',直接写‘/api/rank/info/?rankid=23784&page=1&json=true’即可
}
}
},
请求数据的时候
image.png
改完后,记得重新npm run dev 一下项目。