萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 跨域解決方案全景指南:JSONP、CORS、代理、iframe、WebSocket 實戰詳解

前言:同源策略與跨域本質

瀏覽器同源策略限制腳本只能存取相同「協議+域名+埠」的資源。跨域需求普遍存在(微服務架構、第三方 API、多子域應用),本文系統整理五大主流跨域方案,附完整代碼範例與適用場景分析。

方案一:JSONP(JSON with Padding)

原理

<script> 標籤不受同源策略限制。服務端返回可執行的 JavaScript 代碼:callbackName({...data...}),瀏覽器執行時即調用預先定義的回調函數。

前端實作

<script>
function handleResponse(data) {
  console.log('收到資料:', data);
}
</script>
<script src="https://api.example.com/data?callback=handleResponse"></script>

jQuery 封裝

$.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 取代,不建議新專案使用

方案二:CORS(Cross-Origin Resource Sharing) —— 現代標準

後端配置(以 Express 為例)

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-* 標頭。

方案三:後端代理(Server-side Proxy)

架構

前端 → 同源後端代理 → 目標跨域 API。代理服務器不受同源策略限制。

Node.js 代理範例

// 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: '上游服務不可用' });
  }
});

適用場景

  • 隱藏第三方 API 金鑰、簽名邏輯
  • 聚合多個上游 API 回應
  • 繞過瀏覽器 CORS 限制(舊系統無法修改上游)

方案四:iframe + postMessage

原理

嵌入跨域 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>

iframe 頁面 (proxy.example.com/frame.html)

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 跨域

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));

後端(Node.js ws 库)


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' }));
});

方案選型決策樹

  1. 能控制後端? → 首選 CORS(標準、安全、支援所有 HTTP 方法)。
  2. 無法控制後端,僅需 GET 讀取公開資料? → 可用 JSONP(但優先尋找 CORS 替代)。
  3. 需隱藏金鑰/聚合 API/繞過不可控 CORS? → 後端代理。
  4. 需跨域共享 Session/存取 iframe 內容? → iframe + postMessage(注意 CSP 與 X-Frame-Options)。
  5. 即時雙向通訊? → WebSocket。

安全檢查清單

  • CORS origin 嚴格白名單,避免 * 配合 credentials: true。
  • JSONP 端點嚴格驗證 callback 參數格式(僅允許字母數字底線)。
  • 代理服務器實施速率限制、輸入驗證、上游超時控制。
  • postMessage 必須驗證 event.origin。

總結

現代 Web 開發以 CORS 為首選,輔以後端代理處理特殊場景。JSONP 已逐漸退出歷史舞台,iframe postMessage 適用於嵌入式跨域通訊,WebSocket 則是即時應用的標準選擇。理解各方案原理與權衡,才能根據業務需求做出最佳架構決策。

copyright © 萬盛學電腦網 all rights reserved