node.js - 对 Node 后端/Angular 前端中的 socket.io 事件系统进行故障排除
问题描述
我需要在 Node 后端设置一个简单的事件系统,以在某些事件发生时通知客户端(Angular 应用程序)(当用户更改他的个人资料照片时)。我在后端使用 socket.io 库,在前端使用等效的“ngx-socket-io”。这是我到目前为止所做的:
后端 - 'bin/www'(服务器初始脚本)
// 'server' is created using 'http.createServer()'
const io = require('socket.io')(server);
// Set the socket.io object in the main app object to access it from anywhere
app.set('socketio', io);
io.on('connection', socket => {
logger.debug('Socket connected: ', socket.id);
socket.on('disconnect', () => {
logger.debug('Socket disconnected: ', socket.id);
});
});
后端 - 'controllers/user.js'(用户路由控制器)
controller.changeProfilePhoto = function(req, res) {
// Socket IO object
const socketio = req.app.get('socketio');
// Do the stuff to change the profile photo...
if(socketio) {
socketio.emit("appevent", { msg: 'Profile photo updated', user: req.body.userId });
}
}
前端 - 'services/app-events.service.ts'(应用事件服务)
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AppEventsService {
constructor(private socket: Socket) { }
sendMessage(msg: string) {
this.socket.emit("appevent", msg);
}
getMessage(): Observable<any> {
return this.socket.fromEvent("appevent");
}
}
我订阅了getMessage
在发生某些事件时需要更新的组件,但我没有收到任何事件。在后端,每次客户端连接时我都会看到一条消息:
套接字连接:Wv8-DXqMaPi_dhRIAAAA
有什么问题?
提前致谢!
解决方案
该问题与 socket.io 无关,而是与从客户端到达后端的方式有关。我正在使用反向代理来避免在防火墙中为 API 打开额外的端口,并且我在 socket.io 连接中使用了错误的 URL。
如果有人需要它,这是proxy.conf.json
我正在使用的文件:
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"pathRewrite": {
"^/api": ""
}
},
"/socket.io": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"ws": true
}
}
socket.io 连接的 URL 必须是客户端的基地址,如下例所示:
- 客户端地址:http://localhost:4200
- Socket.io 将为其添加一个新端点:http://localhost:4200/socket.io
- 按照代理配置中的规则,“/socket.io”将被翻译为“ http://localhost:3000/socket.io ”
希望有帮助,加油!
推荐阅读
- reactjs - 在 github 中查询有关 react 应用程序的工作流失败的问题
- android - android - getString 导致从 strings.xml 获取错误
- python - 从 keras.backend.tensorflow_backend 导入 set_session
- php - 使用php自动刷新特定的id元素
- c++ - 如何初始化和访问 const char* const*
- r - R install.package() 使用 options() 参数化 download.file()
- airflow-scheduler - 为 apache 气流安装 python 依赖项
- java - Corda RPC client external dependencies
- c++ - c ++:在'dt2'中请求成员'get_date',它是非类类型'DateTime(*)()
- c++ - 我可以在“if 语句”中声明变量吗?