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

时间:2019-01-14 09:02:49

标签: angular7 ionic4

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

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

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

我已遍历代码并确认login()仅被调用一次,我的HttpInterceptor仅被调用一次,远程请求仅被发送一次。

我已经上传this image来帮助解释正在发生的事情。您可以看到只有1个远程请求已执行,但2个响应已记录到控制台。

此问题仅在几个小时前开始。我一直在努力让离子服务与CORS配合使用,我尝试使用proxy.conf.jsonproxy.js,但是由于无法访问API,我无法访问。出于开发目的,我已使用this extension在Chrome中禁用了CORS,因为一旦在移动设备上运行该应用程序便不需要CORS。

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

  1. 在Chrome中禁用了Allow-Control-Allow-Origin:*扩展程序,问题仍然存在
  2. 我从app.module.ts中删除了HttpInterceptor,问题仍然存在
  3. 我尝试了其他远程URL(甚至是本地主机),问题仍然存在
  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;

  }));

}

如果有帮助,这里是我的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

  });

}
export class AuthInterceptor implements HttpInterceptor {

  constructor() { }

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

    // Check auth here...

    return next.handle(request);

  }

}

我希望return res;仅被调用一次。

3 个答案:

答案 0 :(得分:0)

请使用单个return语句,而不要返回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;

  }));

}

答案 1 :(得分:0)

原来我需要更改

date

到以下

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;

  }));

}

答案 2 :(得分:0)

在您提到的代码中,但您所描述的内容,我看不到任何问题。看来您已经为http请求设置了一些选项,并且响应是观察事件而不是响应。

options: {
    headers?: HttpHeaders | {[header: string]: string | string[]},
    observe?: 'body' | 'events' | 'response',
    params?: HttpParams|{[param: string]: string | string[]},
    reportProgress?: boolean,
    responseType?: 'arraybuffer'|'blob'|'json'|'text',
    withCredentials?: boolean,
  }

observe选项指定要返回的响应量。 This link might be helpful