javascript - 如何使用 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 调用中获取该数据。
解决方案
推荐阅读
- autodesk-forge - 使用自定义扩展查看器 Autodesk Forge
- flutter - 指定笔画宽度时未连接阿拉伯文本
- javascript - 为什么这个 puppeteer 的异步函数语法?
- php - 如何使用 MySQLi 和 PHP 从 MySQL DB 中获取单行?
- c# - HTTPClient.PostAsync 仅在发布较大文件时引发异常
- javascript - 关闭和回调函数Javascript
- facebook - 如何获取 Facebook Marketplace 目录产品的公共 URL
- f# - 使用 Elmish.wpf/F#,如何在 WPF 中将字符串选项显示为字符串或 null,而不是“Some(string)”?
- powershell - 如何从 Foreach 中的第二个 CSV 检索关联值
- angular - 离子页脚最佳实践