首页 > 解决方案 > 如何使用 SocketsIO 从 NodeJS API 调用向前端发送数据

问题描述

我制作了 Electron 应用程序,它使用Socket.IO在后端(NodeJS)和前端(Jquery)之间进行通信。

我已经从

io.on('connection', (socket) => { socket.emit (.....) })

我的问题是我无法从 API 调用发送数据。

让我告诉你一个例子。

const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require("socket.io");
const io = new Server(server);

app.set('socketIo', io);

app.get('/api/run', (req, res) => {
    const ioEmitter = req.app.get("socketIo");
    ioEmitter.emit('data', 'some data'); // not working
    // ioEmitter.to(~some socket id~).emit('data', 'some-data')
    // not working either. I can't get anything to client side
})

客户端代码

socket.on('data', (msg) => {
    console.log(msg)
})

我(项目)必须从 API 调用中获取该数据。

标签: javascriptnode.jssocket.io

解决方案


推荐阅读