0
0

More than 1 year has passed since last update.

socket.ioでCORSを設定する

Last updated at Posted at 2021-10-17

socket.ioのCORSはv3以降は有効にする必要があるようです。

サーバ側

「socketio」の引数で「cors」を設定します

server.js
const socketio = require('socket.io');
const http = require('http');

// origin は function を設定できるようです
// ですので、正規表現を使用し、パターンマッチをさせることもできます。
const socketOptions = {
  cors: {
    origin: function (origin, fn) {
      const isTarget = origin !== undefined && origin.match(/^https?:\/\/www\.test\.net/) !== null;
      return isTarget ? fn(null, origin) : fn('error invalid domain');
    },
    credentials: true
  }
};

const app = function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('...');
};

// 第一引数のオプションは必要に応じてcertなどを設定
const server = http.createServer({}, app);
const io = socketio(server, socketOptions);

server.listen(8080);

クライアント側

第二引数で「withCredentials」を設定します

client.js
  socket = io.connect('https://xxx.xxx/xxx', {
    withCredentials: true
  });
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0