为什么会出现跨域?
原因是受到浏览器同源策略的限制
同源指的是协议相同、域名相同,端口相同
域的组成:协议 + 域名 + 端口
跨域:不同源的网址之间的通信会出现跨域,一旦出现跨域,请求响应会被浏览器拒绝。
其实跨域和跨源就是同个意思。
浏览器控制台会打印:
Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
目前,如果非同源,共有三种行为受到限制。
(1) 无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB。
(2) 无法接触非同源网页的 DOM。
(3) 无法向非同源地址发送 AJAX 请求(可以发送,但浏览器会拒绝接受响应)。
同源政策的目的,是为了保证用户信息的安全,防止恶意的网站窃取数据。
怎么解决?
1、JSONP
jsonp:动态创建script标签,src不受同源政策限制,可以跨域请求。
特点:简单易用没有兼容性问题,老式浏览器全部支持,服务端改造非常小。
缺点:1、只能发送get请求。2、需要后端定义callback函数
后端node服务端:
const http = require('http')
const app = http.createServer((req, res) => {
if (req.url === '/favicon.ico') {
return
}
const myUrl = new URL(req.url, 'http://localhost:8080')
switch(myUrl.pathname){
case '/list':
// 响应请求头
res.writeHeader(200, {'Content-Type': 'text/html', 'charset': 'utf-8'})
let search = {}
myUrl.searchParams.forEach((value, name) => {
search[name] = value
})
res.end(`${search.callback}(${JSON.stringify(search)})`)
break
default:
res.end("text('404')")
}
})
app.listen(8080, () => {
console.log('node Server')
})
前端html页面:
注:这个html页面我是在vscode工具默认的5500端口上运行的,这个例子我访问的是8080端口的服务器,端口不一样。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
// jsonp: 动态创建script标签,src不受同源策略限制
// 解决跨域问题
const createScr = document.createElement('script')
createScr.src = 'http://localhost:8080/list?callback=ushen&year=1999'
document.body.appendChild(createScr)
// 前端需要事先定义好callback函数
function ushen(val) {
console.log(val)
}
</script>
</html>
2、反向代理
架设服务器代理(浏览器请求同源服务器,再由同源服务器请求外部服务)
同源限制主要存在于浏览器,服务器直接的通信不受同源策略限制。我在vue项目请求外部服务器接口时,需要配置反向代理。
vue.config.js
module.exports = defineConfig({
lintOnSave: false,
// 配置反向代理
devServer: {
proxy: {
'/api': {
// target填写外部服务器的地址
target: 'http://www.example.com:3000',
changeOrigin: true,
// 代理 websockets
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
})
至此,所有以"/api"开头的请求地址,都会转变成朝"http://www.example.com:3000"发送ajax请求。
注:vue.config.js配置文件更改,要重启服务器。
3、CORS通信
CORS 是跨源资源分享(Cross-Origin Resource Sharing)的缩写。它是 W3C 标准,属于跨源 AJAX 请求的根本解决方法。相比 JSONP 只能发GET请求,CORS 允许任何类型的请求。可以这么理解,前面两种解决方案都是通过前端来解决,而这个方案实现的关键在于服务端。详见CORS参考
其实每次发起请求,浏览器都会在请求头加上一个Origin
字段。这个字段用来说明发起此次请求是哪个域;当这个请求到了服务器时,服务器会检查这个域,决定是否同意这次请求。服务器响应头有这个么一个字段Access-Control-Allow-Origin
,它用来允许那些域可以访问服务器,浏览器会根据这个字段判断,是否包括发出请求的域,如果不包含Origin
字段所带的域,浏览器就报出跨域错误:
Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
用上面演示的例子稍微改下。
前端发起ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<button>发送请求</button>
</body>
<script>
$("button").click(function() {
$.ajax({
url: 'http://localhost:8080/list?callback=ushen&year=1999',
method: 'get'
}).then(res => {
console.log(res)
})
})
</script>
</html>
后端node服务器
const http = require('http')
const url = require('url')
const app = http.createServer((req, res) => {
if (req.url === '/favicon.ico') {
return
}
console.log(req.url)
const myUrl = new URL(req.url, 'http://localhost:8080')
console.log(myUrl)
switch(myUrl.pathname){
case '/list':
// 响应请求头
res.writeHeader(200, {'Content-Type': 'text/html;charset=utf-8',
// 允许所有跨域请求
"Access-Control-Allow-Origin":"*"
})
let search = {}
myUrl.searchParams.forEach((value, name) => {
search[name] = value
})
console.log(search)
res.end(`${search.callback}(${JSON.stringify(search)})`)
break
default:
res.end("text('404')")
}
})
app.listen(8080, () => {
console.log('node Server')
})
这时候发起请求,请求成功,服务器响应了数据
再来看看控制台请求和响应头
允许所有域的请求,一般很少人会这么做吧,如果是个人项目做个后台指定一两个域可以访问就够了。
个人能力有限。每天学一点,记录一点!