源
在网页的后台打出window.origin或location.origin可以得到当前源: "juejin.cn" 源=协议+域名+端口号
创建步骤
创建目录
qq-com里面有一个server.js,模拟QQ空间; frank-com里面的server.js,模拟坏人网站;
qq-com
- /index.html是首页
- /qq.js是JS脚本文件
- /friend.json是模拟的好友数据
- 端口监听为8888,访问http://127.0.0.1:8888
frank-com
- /index.html是首页
- /frank.js是JS脚本文件
- 端口监听为9990,访问http://127.0.0.1:9990
server.js文件通过path路径读取index.html,qq.js,friends.json
- 在qq-com中
- 在index.html 中引用qq.js,
- 在qq.js中,用ajax请求friends.json;成功打印出相应内容;
- 在frank-com中:
- 在index.html 中引用frank.js, 在frank.js中,用ajax请求“qq.com:8888/friends.jso…
如何跨域获取别的源的内容,用cors
需要在qq-com 里面的server.js,在路径为path==='friends.json'中加一个
响应头:
response.setHeader('Access-Control-Allow-Origin','http://frank.com:9990')
就可以了。
但是CORS不兼容IE浏览器。
用JSONP
虽然我们不能访问json,但是我们可以在index.html引用,但是js不是数据,但我们用js包含数据,看看怎么样吧
在qq-com中创建friends.js
只用{{data}}进行占位就可以了; 在server.js中,把占位符变成一个真正的数据;
else if(path ==='/friends.js'){
response.statusCode = 200
response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
const string = fs.readFileSync('./public/friends.js').toString()
const data = fs.readFileSync('./public/friends.json').toString()
const string2 = string.replace('{{data}}',data)
response.write(string2)
response.end()
}