伺服器端
範例程式碼:
import express from "express"; import http from "http"; const app = express(); const server = http.createServer(app); const sio = require("socket.io")(server, { handlePreflightRequest: (req, res) => { const headers = { "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to, "Access-Control-Allow-Credentials": true }; res.writeHead(200, headers); res.end(); } }); sio.on("connection", () => { console.log("Connected!"); }); server.listen(3000);
或
var io = require('socket.io')(server, { origins: '*:*'});
或者
io.set('origins', '*:*');
socket io client
設定extraHeaders
,如下:
const socket = require('socket.io-client')(host,{ forceNode:true, transports: ['websocket'], extraHeaders: { Origin: Origindata }, transportOptions: { polling: { extraHeaders: { Origin: Origindata } } } });