瀏覽器同源策略限制腳本只能存取相同「協議+域名+埠」的資源。跨域需求普遍存在(微服務架構、第三方 API、多子域應用),本文系統整理五大主流跨域方案,附完整代碼範例與適用場景分析。
<script> 標籤不受同源策略限制。服務端返回可執行的 JavaScript 代碼:callbackName({...data...}),瀏覽器執行時即調用預先定義的回調函數。
<script>
function handleResponse(data) {
console.log('收到資料:', data);
}
</script>
<script src="https://api.example.com/data?callback=handleResponse"></script>
$.ajax({
url: 'https://api.example.com/data',
dataType: 'jsonp', // 自動處理 callback 參數
success: function(data) { console.log(data); }
});
// 或簡寫
$.getJSON('https://api.example.com/data?callback=?', function(data) {
console.log(data);
});
| 優點 | 缺點 |
|---|---|
| 相容極舊瀏覽器(IE6+) | 僅支援 GET 請求 |
| 實作簡單,無需後端配合 CORS | 安全風險:執行任意 JS 代碼,易遭 XSS 攻擊 |
| 無法攔截錯誤(無 HTTP 狀態碼) | |
| 已被 CORS 取代,不建議新專案使用 |
const cors = require('cors');
app.use(cors({
origin: ['https://app.example.com', 'https://admin.example.com'], // 允許的源
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true // 允許攜帶 Cookie
}));
fetch('https://api.example.com/data', {
credentials: 'include' // 攜帶 Cookie
}).then(res => res.json()).then(data => console.log(data));
非簡單請求(自定義 Header、非 GET/POST/HEAD、Content-Type 非表單類型)會先發送 OPTIONS 預檢,後端需正確響應 Access-Control-Allow-* 標頭。
前端 → 同源後端代理 → 目標跨域 API。代理服務器不受同源策略限制。
// proxy.js
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/api/proxy/external', async (req, res) => {
try {
const response = await axios.get('https://external-api.com/data', {
params: req.query,
headers: { 'Authorization': `Bearer ${process.env.API_TOKEN}` }
});
res.json(response.data);
} catch (err) {
res.status(502).json({ error: '上游服務不可用' });
}
});
嵌入跨域 iframe,雙方透過 window.postMessage 通訊。
<iframe id="proxyFrame" src="https://proxy.example.com/frame.html" style="display:none"></iframe>
<script>
const frame = document.getElementById('proxyFrame');
frame.onload = () => {
frame.contentWindow.postMessage({ action: 'fetch', url: '/data' }, 'https://proxy.example.com');
};
window.addEventListener('message', (event) => {
if (event.origin !== 'https://proxy.example.com') return;
console.log('收到代理回應:', event.data);
});
</script>
window.addEventListener('message', async (event) => {
if (event.origin !== 'https://app.example.com') return;
const { action, url } = event.data;
if (action === 'fetch') {
const res = await fetch(url, { credentials: 'include' });
const data = await res.json();
event.source.postMessage({ success: true, data }, event.origin);
}
});
WebSocket 協議(ws://, wss://)握手階段雖受同源策略限制,但建立連線後雙向通訊不再受限。適用於即時推播、長連線場景。
const ws = new WebSocket('wss://api.example.com/socket');
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', channel: 'news' }));
ws.onmessage = (event) => console.log('即時訊息:', JSON.parse(event.data));
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws, req) => {
// 可檢查 req.headers.origin 實施白名單
ws.on('message', (msg) => { /* 處理 */ });
ws.send(JSON.stringify({ type: 'welcome' }));
});
origin 嚴格白名單,避免 * 配合 credentials: true。callback 參數格式(僅允許字母數字底線)。event.origin。現代 Web 開發以 CORS 為首選,輔以後端代理處理特殊場景。JSONP 已逐漸退出歷史舞台,iframe postMessage 適用於嵌入式跨域通訊,WebSocket 則是即時應用的標準選擇。理解各方案原理與權衡,才能根據業務需求做出最佳架構決策。