node.js - Angular 8 - 无法让 httpClient POST 与 Socket.io 一起完成其工作?

标签 node.js angular sockets

我有一个可用的 AngularJS 前端和一个用 node.js'express、http 和 socket.io 编写的后端。现在我想将前端转换为 Angular 8 并进一步使用旧的后端(因为它运行良好并且需要大量工作)。

现在我使用 ngx-socket-io 进行聊天通信,并希望使用 Angular 的 HttpClientModule 进行 API 请求。

app.module.ts

...
import { HttpClientModule } from '@angular/common/http';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
...
const apiConfig: SocketIoConfig = { url: 'http://localhost:8000', options: {} };

@NgModule({declarations: [...], imports: [
  ...
  HttpClientModule,
  SocketIoModule.forRoot(apiConfig)
]
...

登录.组件.ts

import { CommunicationService } from '../services/communication.service';
...
constructor(
  ...
  private comm: CommunicationService
) { }

submitForm() {
  const formValue = this.loginGroup.value;
  this.comm.checkAuthentication(formValue.userName, formValue.password);
}

通信.service.ts

import { Socket } from 'ngx-socket-io';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
...
@Injectable({
  providedIn: 'root'
})
export class CommunicationService {
  private api = 'http://localhost:8001/api';
  constructor(private socket: Socket, private http: HttpClient) { }

  checkAuthentication(username: string, password: string) {
    console.log(`send: ${username}, ${password}`);
    const test = this.http.post<any>(
      `${this.api}/authenticate`,
      { username, password }
    ).pipe(
      catchError(this.errorHandler)
    );
    console.log(test);
    const test2 = this.http.get(
      `${this.api}/users`
    );
    console.log(test2);
  }
  ...
}

我可以看到请求发出,但在服务器端它没有到达。我会在那里看到一个日志条目。如果我使用 postman ,我会看到请求到达,因此服务器仍然可以工作。

我可以想象,Angular 在端口 8000 上不断打开与 socket.io 的连接时出现问题,然后使用相同的套接字来发出请求。可能是这样吗?是的,该网站使用聊天(在套接字上工作)和一些其他通过 API 请求工作的功能。所以我需要这两个选项一起工作。

编辑:我将api的端口更改为8001,但仍然没有响应。 console.log 显示了一个几乎完整的空对象:

{…} ​_isScalar:假 ​操作符:Object { 选择器:errorHandler() , 捕捉: {…} } ​来源:对象 { _isScalar: false,来源:{…},运算符:{…} }

最佳答案

Http 客户端返回一个 observable,因此您必须订阅它才能捕获数据,请检查 this ref

this.http.post<any>(
      `${this.api}/authenticate`,
      { username, password }
    ).pipe(
      catchError(this.errorHandler)
    ).subscribe((data) => {
         console.log(data) 
    });

关于node.js - Angular 8 - 无法让 httpClient POST 与 Socket.io 一起完成其工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57740095/

相关文章:

node.js - Firebase Cloud Functions 中抛出未处理的错误

javascript - 带括号的 ES6 箭头函数

javascript - 如何传递具有动态引用angular2的元素?

angular - 根据用户选择顺序保存多个选择的 ngModel 绑定(bind)值

c++ - 在 C++ 中使用 connect() 时设置超时

node.js - 在 Vagrant box 中安装 NVM/NodeJs/EmberJS

node.js - 如何将 AWS lambda 函数变成自己的 https 端点?

ruby-on-rails - Rails 5 actioncable 作为独立服务器

node.js - 如何在浏览器关闭时让我的应用程序注销?

mysql - 无法通过套接字连接到本地MySQL服务器