http.request 在实际响应之前返回“{ type: 0 }”

o7_*_*ute 5 ionic4 angular7

每次我提交登录表单时,方法return res;中的Login()代码(见下文)都会执行两次。

第一个响应是一个简单的对象{ type: 0 },第二个响应是我正在寻找的实际响应。

为什么会return res;被叫两次?我该如何防止这种情况发生?

我已单步执行代码并确认login()仅被调用一次,我的HttpInterceptor仅被调用一次,并且远程请求仅被发送一次。

我上传了这张图片来帮助解释发生了什么。您可以看到仅执行了 1 个远程请求,但已将 2 个响应记录到控制台。

这个问题是几个小时前才开始出现的。我一直在努力让离子服务与 CORS 一起使用,我尝试使用proxy.conf.jsonproxy.js无法访问 API,我无法允许访问。出于开发目的,我使用此扩展在 Chrome 中禁用了 CORS ,因为一旦我在移动设备上运行该应用程序,它就不需要 CORS。

我尝试过的其他故障排除:

  1. 在 Chrome 中禁用了 Allow-Control-Allow-Origin: * 扩展,问题仍然存在
  2. 我从 app.module.ts 中删除了 HttpInterceptor,问题仍然存在
  3. 我尝试了不同的远程 URL(甚至是 localhost),但问题仍然存在
  4. 关闭 Chrome 并重新启动 PC,问题仍然存在
  5. 尝试使用FireFox,问题依然存在
  6. 我创建了一个新的 Ionic4 项目并复制/粘贴相同的代码,问题仍然存在
  7. 我在另一台机器上尝试使用 Chrome,问题仍然存在

这是我login()在我的方法中订阅的可观察对象onSubmit()

login(username: string, password: string) {

  const body = new FormData();

  body.append('username', username);
  body.append('password', password);

  const request = new HttpRequest('POST', '[URL]', body);

  return this.http.request(request)
  .pipe(map(res => {

    return res;

  }));

}
Run Code Online (Sandbox Code Playgroud)

这是我的onSubmit()HttpInterceptor如果有帮助的话。

onSubmit () {

  this.isSubmitted = true; // I've put a break point here to make sure this method is called once

  if (!this.login.valid) {

    return;

  }

  this.authenticationService.login(this.login.value.username, this.login.value.password).subscribe((res: any) => {

  console.log(res); // this is the log that is displayed in the above screen shot

  });

}
Run Code Online (Sandbox Code Playgroud)
export class AuthInterceptor implements HttpInterceptor {

  constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // Check auth here...

    return next.handle(request);

  }

}
Run Code Online (Sandbox Code Playgroud)

我预计return res;只会接到一次电话。

小智 0

请使用单个返回语句而不是返回 2 次尝试使用下面的代码,谢谢

login(username: string, password: string) {

  const body = new FormData();

  body.append('username', username);
  body.append('password', password);

  const request = new HttpRequest('POST', '[URL]', body);

  this.http.request(request)
  .pipe(map(res => {

    return res;

  }));

}
Run Code Online (Sandbox Code Playgroud)