同源策略
-
浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权的情况下,不能读写对方的资源。正常情况下只有同源发的请求浏览器才会接受.
H}$JAA%3945MBU4R0VR883W.jpg
本域指的是?
- 同协议:如都是http或者https
- 同域名:如都是http://jirengu.com/a 和http://jirengu.com/b
- 同端口:如都是80端口
如: - http://jirengu.com/a/b.js 和 http://jirengu.com/index.php (同源)
不同源的例子:
- http://jirengu.com/main.js 和 https://jirengu.com/a.php (协议不同)
- http://jirengu.com/main.js 和 http://bbs.jirengu.com/a.php (域名不同,域名必须完全相同才可以)
- http://jiengu.com/main.js 和 http://jirengu.com:8080/a.php (端口不同,第一个是80)
需要注意的是: 对于当前页面来说页面存放的 JS 文件的域不重要,重要的是加载该 JS 页面所在什么域,也就是指当前js执行环境所在页面的url,而不是指js文件的地址,当前页面的url和ajax请求的url能对上号才可以.

报错范例:
给host文件添加记录
127.0.0.1 a.com
127.0.0.1 b.com
假设访问a.com,b.com 时候相当于访问本机,借此实现一个场景.浏览器是a.com,接口是b.com.虽然对应的都是本机 可域名并不一样.
var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')
http.createServer(function (req, res) {
var pathObj = url.parse(req.url, true)
console.log(pathObj)
switch (pathObj.pathname) {
case '/getWeather':
res.end(JSON.stringify({
beijing: 'suny'
}))
break;
default:
fs.readFile(path.join(__dirname, pathObj.pathname), function (e, data) {
if (e) {
res.writeHead(404, 'not found')
res.end('<h1>404 Not found</h1>')
} else {
res.end(data)
}
})
}
}).listen(8080)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>hello world</h1>
<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://b.com/getWeather', true)
xhr.send()
xhr.onload = function () {
console.log(xhr.responseText)
}
</script>
</body>
</html>
网友评论