【问题标题】:Angular 6: Console Error: Backend returned code 200 ErrorAngular 6:控制台错误:后端返回代码 200 错误
【发布时间】:2018-12-17 21:16:00
【问题描述】:

我正在尝试使用联系表单将数据发送到数据库,它正在将数据发送到数据库,但是之后,在显示成功消息的地方显示错误消息。我还尝试使用数据库中预定义的用户详细信息登录。但它也在前端和控制台消息中显示错误处理消息“后端返回代码 200,正文为:[object Object]”。我怎样才能得到这个的解决方案。这些错误显示了这两种情况。请帮忙....,它是 cmspage.service.ts 文件:

import { Injectable } from '@angular/core';
import { Page } from './page';
import { Contact } from './contact';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpBackend } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class CmspageService {

  ServerUrl = environment.baseUrl;
  errorData: {};

  httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json'})
  };

  private http: HttpClient;

  constructor(handler: HttpBackend) {
      this.http = new HttpClient(handler);
  }


  contactForm(formdata: Contact) {
    return this.http.post<Contact>(this.ServerUrl + 'api/contact', formdata, this.httpOptions)
    .pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }
}

这里我在 environment > environment.ts 文件中设置了 baseUrl, 联系表格 html

<section class="cmspage mtb-40">
  <div class="container">
    <div class="page-desc" [hidden]="submitted">
      <div class="row justify-content-center">
        <div class="col-md-8">
          <h1>Contact</h1>
          <form (ngSubmit)="onSubmit()" #contactForm="ngForm">
            <div class="form-group">
              <input type="text" name="name" id="name" [(ngModel)]="model.name" class="form-control" placeholder="Name" required #name="ngModel">
              <div *ngIf="name.invalid && (name.dirty || name.touched)" class="error">
                <div *ngIf="name.errors.required">
                  Name is required.
                </div>
              </div>
            </div>
            <div class="form-group">
              <input type="text" name="email" id="email" [(ngModel)]="model.email" class="form-control" placeholder="E-Mail" required email #email="ngModel">
              <div *ngIf="email.invalid && (email.dirty || email.touched)" class="error">
                <div *ngIf="email.errors.required">Email is required.</div>
                <div *ngIf="email.errors.email">Email must be a valid email address.</div>
              </div>
            </div>
            <div class="form-group">
              <input type="text" name="phone" id="phone" [(ngModel)]="model.phone" class="form-control" placeholder="Phone">
            </div>
            <div class="form-group">
              <textarea name="message" id="message" [(ngModel)]="model.message" rows="5" class="form-control" placeholder="Message" required #message="ngModel"></textarea>
              <div *ngIf="message.invalid && (message.dirty || message.touched)" class="error">
                <div *ngIf="message.errors.required">Message is required.</div>
              </div>
            </div>
            <div class="form-group">
              <button [disabled]="!contactForm.form.valid" class="btn btn-success">Send Message</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="service-error" *ngIf="error">
      <h1>{{error.errorTitle}}</h1>
      <h3>{{error.errorDesc}}</h3>
    </div>
    <div [hidden]="!submitted" class="contact-message">
      <div *ngIf="model.id" class="contact-success">
        <h2 class="success">Success!</h2>
        <h4>Contact form has been successfully submitted.</h4>
        <br />
        <button (click)="gotoHome()" class="btn btn-info">Go to Home</button>
      </div>
    </div>
  </div>
</section>

这里也出现错误,这是 auth.service.ts,用于登录到管理仪表板

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  serverUrl = environment.baseUrl;
  errorData: {};

  isLoggedIn = false;

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(username: string, password: string) {
    return this.http.post<any>(`${this.serverUrl}api/login`, {username: username, password: password})
    .pipe(map(user => {
        if (user && user.token) {
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.isLoggedIn = true;
        }
      }),
      catchError(this.handleError)
    );
  }

  getAuthorizationToken() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    return currentUser.token;
  }

  logout() {
    localStorage.removeItem('currentUser');
    this.isLoggedIn = false;
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

}

【问题讨论】:

  • 在 Chrome 中进入“网络” -> 重新加载页面 -> 发送一个请求,您会看到它会出现,您可以查看从服务器返回的内容
  • 可能是json格式不正确,能否显示请求响应正文
  • 如果你取出handler: HttpBackend 部分,它的行为会有什么不同吗?
  • 如果服务器返回 200 且没有正文,HttpClient 将出错。如果是这种情况,服务器应该返回 204
  • @Jake11 哪个部分负责请求响应正文?

标签: javascript angular angular6 angular-services


【解决方案1】:

对我来说,感觉后端正在成功返回。因此,您将获得 200 状态。也因此,您在网络选项卡中看不到任何错误。因为没有错误。当对服务器的调用成功时,您正在记录状态。所以代码正在做它应该做的事情。但我能说的是它没有按预期获取数据。服务器未按预期返回数据。服务器可能会返回一个数组(或对象列表),但您并不期望在前端出现这种情况。尝试检查服务器返回的内容。查看 api 签名,或者如果您有后端代码,请查看它返回的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多