You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket.IO跨域问题:代理服务器与浏览器WebSocket连接失败

WebSocket连接CORS拦截问题(TikTok API实时图表场景)

问题描述

在代理服务器与浏览器间建立WebSocket连接时触发CORS拦截错误,具体提示:

Access to XMLHttpRequest at 'url' from origin 'url' has been blocked by CORS policy.

核心需求:通过调用TikTok API,每分钟获取用户粉丝数、点赞数,并更新前端图表数据。

服务器端代码

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const nodemon = require('nodemon');
const bodyParser = require('body-parser');
const fetch = require('node-fetch');
const cors = require('cors');
const { Server } = require("socket.io");
const io = new Server(server);

app.use(bodyParser.json())

app.use(
    cors({
        origin: "https://fluence.noit.eu"
    })
);

io.on('connection', (socket) => {
    console.log('A user connected');

    // Handle the real-time statistic request from the client
    socket.on('sendAccessToken', (accessToken) => {
        fetch('https://open.tiktokapis.com/v2/user/info/?fields=follower_count,likes_count', {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            // Emit the data back to the client
            socket.emit('realTimeStatisticData', data);
        })
        .catch(error => {
            // Emit the error back to the client
            socket.emit('realTimeStatisticError', error);
        });
    });

    // You can add more socket event handlers here

    // Example: Send a message to the connected client
    socket.emit('message', 'Welcome to the real-time statistics server');

    // Example: Listen for a client message and broadcast it to all clients
    socket.on('chatMessage', (message) => {
        io.emit('chatMessage', message);
    });

    // Handle disconnect
    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
});

app.listen()

浏览器端代码

let accessToken = JSON.parse('<?php echo isset($_COOKIE["tiktok_access_token"]) ? json_encode($_COOKIE["tiktok_access_token"]) : json_encode($accessToken) ?>');

const socket = io('https://fluence-api.noit.eu');

socket.on('connect', () => {
    // When the WebSocket connection is established, send the access token to the server
    socket.emit('sendAccessToken', accessToken);
});

socket.on('realTimeStatisticData', (data) => {
    // Handle the received data here
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();

    if (minutes < 10) {
        minutes = String(date.getMinutes()).padStart(2, '0');
    }

    let time = hours + ":" + minutes;

    // Extract necessary information from data
    let followers = data.data.user.follower_count;
    let likes = data.data.user.likes_count;

    // Update the charts with the new data
    followersLive.data.labels.push(time);
    followersLive.data.datasets[0].data.push(followers);
    followersLive.update();

    likesLive.data.labels.push(time);
    likesLive.data.datasets[0].data.push(likes);
    likesLive.update();
});

已尝试的解决方案

  • 客户端添加Socket.IO配置:{ transports: ['websocket'] }
  • 服务器端通过cors中间件设置允许的源为https://fluence.noit.eu

内容的提问来源于stack exchange,提问作者LackOnUsernameIdeas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 05:25:08