解决跨域问题的几种办法

发布时间:2023-05-23

一、利用Jsonp

Jsonp是一种利用<script>标签实现跨域传输数据的方法。在ajax跨域请求时,json数据通过回调函数的方式传递回来,从而实现跨域数据传输。

function jsonp(url, callback){
    var script = document.createElement('script');
    script.src = url;
    document.head.appendChild(script);
    window.callback = function(data){
        callback(data);
        document.head.removeChild(script);
    };
}
jsonp('http://example.com/api/data?callback=callback', function(data){
    console.log(data);
});

二、使用CORS(Cross-Origin Resource Sharing)

CORS是一种跨域资源共享的机制。通过在服务器端设置Access-Control-Allow-Origin响应头,来允许特定的源站点访问指定的资源。

// nodejs express服务器设置CORS
const express = require('express');
const app = express();
app.use(function(req,res,next){
    res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.setHeader('Access-Control-Allow-Methods', 'GET');
    next();
});
app.get('/api/data', function(req,res){
    res.json({data: 'hello'});
});
app.listen(3000);

三、使用nginx代理

通过在nginx服务器上配置反向代理服务器,来实现跨域请求。在nginx上添加一个location项,将请求转发到目标服务器,从而达到跨域效果。

// nginx反向代理配置
server {
    listen 80;
    server_name example.com;
    location /api {
        proxy_pass http://localhost:3000; // 目标服务器地址
        add_header Access-Control-Allow-Origin http://example.com; // 设置允许跨域的源站点
        add_header Access-Control-Allow-Headers Content-Type; // 设置允许跨域的请求头
        add_header Access-Control-Allow-Methods GET; // 设置允许跨域的请求方法
    }
}

四、使用iframe

通过在页面上嵌入一个隐藏的iframe,来进行跨域数据交互。在iframe中加载目标页面,并将需要传递的数据作为url的参数传递过去。目标页面通过读取url参数,获取传递的数据。

// 发送方页面
<iframe id="iframe1" src="http://example.com/receiver.html"></iframe>
var iframe = document.getElementById('iframe1');
var data = {name: 'Tom', age: 18};
iframe.src = 'http://example.com/receiver.html?' + encodeURIComponent(JSON.stringify(data));
// 接收方页面
var data = JSON.parse(decodeURIComponent(window.location.search.substring(1)));
console.log(data);

五、使用WebSocket

WebSocket是一种全双工通信协议,能够在不同的域名之间进行数据传输。通过在服务器上部署WebSocket服务端,来实现跨域数据交互。

// 前端WebSocket客户端
var socket = new WebSocket('ws://example.com');
socket.onopen = function(){
    socket.send('Hello WebSocket!');
};
socket.onmessage = function(event){
    console.log(event.data);
};
// 后端WebSocket服务端
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 8080});
wss.on('connection', function connection(ws){
    ws.on('message', function incoming(message){
        console.log('received: %s', message);
        ws.send('received');
    });
});