我在代理服务器和浏览器之间建立 Websocket 连接时遇到问题。这个想法是通过向 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();
});
我尝试将 { Transports : ['websocket'] } 添加到
const socket = io('https://echo.websocket.events', { transports : ['websocket'] });
。
我还尝试在服务器端设置cors origin。
在服务器端,您可以将 CORS 添加到套接字本身。
const io = new Server(server, {
cors: {
origin: process.env.WEB_URL,
methods: ['GET', 'POST'],
},
});
将 CORS 添加到您的套接字应该可以解决您的问题。环境变量
process.env.WEB_URL
基本上是前端的 URL。