同源策略
同源策略,是浏览器为了保护用户信息安全的一种安全机制。所谓的同源就是指代通信的两个地址(例如服务端接口地址与浏览器客户端页面地址)之间比较,是否协议、域名(IP)和端口相同。不同源的客户端脚本[javascript]在没有明确授权的情况下,没有权限读写对方信息。
ajax本质上还是javascript,是运行在浏览器中的脚本语言,所以会被受到浏览器的同源策略所限制。
前端地址:http://www.oldboy.cn/index.html | 是否同源 | 原因 |
|---|---|---|
http://www.oldboy.cn/user/login.html |
是 | 协议、域名、端口相同 |
http://www.oldboy.cn/about.html |
是 | 协议、域名、端口相同 |
https://www.oldboy.cn/user/login.html |
否 | 协议不同 ( https和http ) |
http:/www.oldboy.cn:5000/user/login.html |
否 | 端口 不同( 5000和80) |
http://bbs.oldboy.cn/user/login.html |
否 | 域名不同 ( bbs和www ) |
同源策略针对ajax的拦截,代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
</head>
<body>
<div id="app">
<button @click="get_music">点击获取天气</button>
</div>
<script>
let vm = new Vue({
el:"#app",
data:{},
methods:{
get_music(){
axios.get("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=我的中国心")
.then(response=>{
console.log(response);
}).catch(error=>{
console.log(error.response)
});
}
}
})
</script>
</body>
</html>
上面代码运行错误如下:
Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
上面错误,关键词:Access-Control-Allow-Origin。只要出现这个关键词,就是访问受限。出现同源策略的拦截问题。

浙公网安备 33010602011771号