Angular 6:控制台错误:后端返回了代码200错误

时间:2018-12-17 21:16:00

标签: javascript angular angular6 angular-services

我正在尝试使用联系表将数据发送到数据库,它正在将数据发送到数据库,但是之后显示成功消息的同时显示错误消息。我还尝试使用数据库中的预定义用户详细信息登录。但是它还在前端和控制台消息“后端返回的代码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.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);
  }

}

1 个答案:

答案 0 :(得分:0)

在我看来,后端正在成功返回。因此,您的状态为200。同样由于这个原因,您在“网络”标签中看不到任何错误。因为没有错误。到服务器的调用成功时,您正在记录状态。因此,代码正在执行应做的事情。但是我能说的是它没有获得预期的数据。服务器未按预期返回数据。服务器可能返回了一个数组(或对象列表),但您并不期望它在前端。尝试检查服务器返回什么。查看api签名,或者如果您有后端代码,请查看它返回的内容。