在前端开发中,常见的跨域解决方案有以下8种:
标签的跨域特性,通过动态创建
标签,请求一个带有回调函数的接口,服务器返回的数据会作为回调函数的参数传入,从而实现跨域请求。function jsonp(url, callback) {
const script = document.createElement('script');
script.src = url + '?callback=' + callback;
document.body.appendChild(script);
}
jsonp('http://api.example.com/data', 'handleResponse');
function handleResponse(data) {
console.log(data);
}
// 服务器响应头设置
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
// 前端请求
fetch('http://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
// 服务器端代理
app.use('/api', proxy({ target: 'http://api.example.com', changeOrigin: true }));
// 前端请求
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
const socket = new WebSocket('ws://api.example.com');
socket.onmessage = function(event) {
console.log(event.data);
};
window.postMessage
方法在不同窗口之间进行跨域通信,可以实现跨域数据传递和消息通知。// 窗口A发送消息
window.postMessage('Hello', 'http://example.com');
// 窗口B接收消息
window.addEventListener('message', function(event) {
if (event.origin === 'http://example.com') {
console.log(event.data);
}
});
const socket = new WebSocket('ws://api.example.com');
socket.onopen = function() {
socket.send('GET /data HTTP/1.1\r\nHost: api.example.com\r\n\r\n');
};
socket.onmessage = function(event) {
console.log(event.data);
};
location /api {
proxy_pass http://api.example.com;
}
CORS:
反向代理:
WebSocket:
postMessage:
WebSocket + CORS:
Nginx反向代理:
WebRTC: