同源策略
-
瀏覽器出于安全方面的考慮很泊,只允許與本域下的接口交互乙嘀。不同源的客戶端腳本在沒(méi)有明確授權(quán)的情況下凳宙,不能讀寫(xiě)對(duì)方的資源。正常情況下只有同源發(fā)的請(qǐng)求瀏覽器才會(huì)接受.
H}$JAA%3945MBU4R0VR883W.jpg
本域指的是?
- 同協(xié)議:如都是http或者h(yuǎn)ttps
- 同域名:如都是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 (協(xié)議不同)
- http://jirengu.com/main.js 和 http://bbs.jirengu.com/a.php (域名不同茬故,域名必須完全相同才可以)
- http://jiengu.com/main.js 和 http://jirengu.com:8080/a.php (端口不同,第一個(gè)是80)
需要注意的是: 對(duì)于當(dāng)前頁(yè)面來(lái)說(shuō)頁(yè)面存放的 JS 文件的域不重要盖灸,重要的是加載該 JS 頁(yè)面所在什么域,也就是指當(dāng)前js執(zhí)行環(huán)境所在頁(yè)面的url,而不是指js文件的地址,當(dāng)前頁(yè)面的url和ajax請(qǐng)求的url能對(duì)上號(hào)才可以.
12384531.jpg
報(bào)錯(cuò)范例:
給host文件添加記錄
127.0.0.1 a.com
127.0.0.1 b.com
假設(shè)訪問(wèn)a.com,b.com 時(shí)候相當(dāng)于訪問(wèn)本機(jī),借此實(shí)現(xiàn)一個(gè)場(chǎng)景.瀏覽器是a.com,接口是b.com.雖然對(duì)應(yīng)的都是本機(jī) 可域名并不一樣.
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>