JSONP/CORS解决跨域问题
一.什么叫做同源策略
同源策略:'协议+域名+端口'相同则同源 浏览器处于安全方面的考虑 只允许同一域名下的接口交互 不同源的客户端浏览器除非授权 否则不能读取对方的资源 不同源则称为跨域
二.JSONP和CORS解决跨域的原理
JSONP:
原理:服务器对返回的值进行函数包装
优点:支持老浏览器
缺点:仅支持GET请求
支持:浏览器允许在img/script/link标签在src或ref标签上写链接 允许跨域
举例:<script src ='http://127.0.0.1:8887/'></script>
CORS:
原理:服务端在返回数据的时候在响应头中加入标识信息
浏览器并不知道是否跨域 仍然发送请求给服务器 服务器在响应头中加上标志信息 如果服务器没有响应头标志信息 浏览器控制台报跨域错误
优点:广泛支持 简单
缺点:不支持老浏览器
举例:服务器响应头Access-Control-Allow-Origin:"*" 允许跨域
三.CORS模拟跨域请求场景
模拟跨域请求:8888端口访问html 向8887端口发送ajax请求时产生跨域
Access-Control-Allow-Origin:参数值
- "*": 任何域名页面都可以访问这个服务器 不安全
- "http://127.0.0.1:8888":某一个域名可以访问 如果是多个域名可以访问 则服务器响应头进行条件判断 这里是发起请求的地址
test.js
<!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>
<script>
//跨域请求:8888提供html请求8887产生跨域
let xhr = new XMLHttpRequest();
xhr.open("GET", 'http://127.0.0.1:8887/')//get请求 向8887端口发送ajax请求
xhr.send()
</script>
</body>
</html>
server1.js
const http = require('http');//http服务
const fs = require('fs')
http.createServer(function (request, response) {
console.log('request come', request.url)
const html = fs.readFileSync('test.html', 'utf8')//读取字符串
response.writeHead(200, 'Content-Type:text/html')
response.end(html)
}).listen(8888)
console.log('success listen 8888')
server2.js
const http = require('http');//http服务
http.createServer(function (request, response) {
console.log('request come', request.url)
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'//'*':任何域名页面都可以访问此服务 Access-Control-Allow-Origin这里通过服务器加了一个响应头---解决跨域
})
response.end("123")
}).listen(8887)
console.log('success listen 8887')
同时启动服务:node server1.js
node server2.js
访问浏览器:localhost:8888
这里服务器上加上一个响应头Access-Control-Allow-Origin解决跨域问题
四.是否所有情况都可以通过Access-Control-Allow-Origin响应头来实现跨域?否
- 允许方法:GET PUST HEAD
- 允许Content-Type: text/plait multipart/form-data application/x-www-form-urlencoded
- 请求头信息,一般自定义请求头不允许使用 需要服务端进行预请求验证
什么是预请求?
定义:用来突破跨域限制的方法
| 预请求响应头 | 含义 |
| Access-Control-Allow-Headers': 'X-Test-Cors' | 允许自定义的请求头可以跨域 |
| Access-Control-Allow-Methods: 'POST, PUT, DELETE' | 允许除了允许以外的跨域方式 |
| 'Access-Control-Max-Age': '1000' | 允许在1000s内允许这种跨域方式 这个时间内不需要反复预请求验证 |
| access-control-allow-credentials: true | 允许客户端携带验证信息 |
| 跨域操作目的:网页中跨域操作保证服务器安全 防止服务器数据被篡改 |
浙公网安备 33010602011771号