處理 CORS
設定
自 Socket.IO v3 以來,您需要明確啟用 跨來源資源共用 (CORS)。
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "https://example.com"
}
});
所有選項都將轉發至 cors 套件。您可以 在此處 找到選項的完整清單。
使用 Cookie (withCredentials) 和其他標頭的範例
// server-side
const io = new Server(httpServer, {
cors: {
origin: "https://example.com",
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
// client-side
import { io } from "socket.io-client";
const socket = io("https://api.example.com", {
withCredentials: true,
extraHeaders: {
"my-custom-header": "abcd"
}
});
注意:如果您的網路應用程式和伺服器不是從同一個埠提供服務,這也適用於本機端
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:8080"
}
});
httpServer.listen(3000);
您可以使用 allowRequest
選項禁止所有跨來源要求
const io = new Server(httpServer, {
allowRequest: (req, callback) => {
const noOriginHeader = req.headers.origin === undefined;
callback(null, noOriginHeader); // only allow requests without 'origin' header
}
});
疑難排解
CORS 標頭「Access-Control-Allow-Origin」遺失
完整錯誤訊息
跨來源請求遭封鎖:相同來源政策禁止讀取遠端資源 .../socket.io/?EIO=4&transport=polling&t=NMnp2WI。(原因:CORS 標頭「Access-Control-Allow-Origin」遺失)。
如果您已正確設定伺服器(請參閱上方),這可能表示您的瀏覽器無法連線至 Socket.IO 伺服器。
下列指令
curl "https://api.example.com/socket.io/?EIO=4&transport=polling"
應會傳回類似
0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
若非如此,請檢查您的伺服器是否正在監聽,且是否實際可透過指定埠連線。
如果 CORS 標頭「Access-Control-Allow-Origin」為「*」,則不支援憑證
完整錯誤訊息
跨來源請求遭封鎖:相同來源政策禁止讀取遠端資源「.../socket.io/?EIO=4&transport=polling&t=NvQfU77」。 (原因:如果 CORS 標頭「Access-Control-Allow-Origin」為「*」,則不支援憑證)
您無法將withCredentials
設定為 true
且 origin: *
,您需要使用特定來源
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "https://my-frontend.com",
// or with an array of origins
// origin: ["https://my-frontend.com", "https://my-other-frontend.com", "http://localhost:3000"],
credentials: true
}
});
預期在 CORS 標頭「Access-Control-Allow-Credentials」中為「true」
完整錯誤訊息
跨來源請求遭封鎖:相同來源政策禁止讀取遠端資源 .../socket.io/?EIO=4&transport=polling&t=NvQny19。(原因:預期在 CORS 標頭「Access-Control-Allow-Credentials」中為「true」)
在這種情況下,withCredentials
在用戶端設定為 true
,但伺服器在cors
選項中遺失 credentials
屬性。請參閱上方範例。