快訊!我的新書今天開始可以在天瓏網路書店預購啦!歡迎大家前往訂購!

 >>>> AI 職場超神助手:ChatGPT 與生成式 AI 一鍵搞定工作難題 <<<<

Socket.io自行增加header

伺服器端

範例程式碼:

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

17年資歷女工程師,專精於動畫、影像辨識以及即時串流程式開發。經常組織活動,邀請優秀的女性分享她們的技術專長,並在眾多場合分享自己的技術知識,也活躍於非營利組織,辦理活動來支持特殊兒及其家庭。期待用技術改變世界。

如果你認同我或想支持我的努力,歡迎請我喝一杯咖啡!讓我更有動力分享知識!