Ошибка Angular5 при получении HTTP-запроса GET - PullRequest
0 голосов
/ 04 июля 2018

Я изучаю angular5, и я изучаю этот урок https://angular.io/tutorial

Я разработчик PHP, использующий ОС Linux, и я пытаюсь получить данные из базы данных MySQL, но у меня появляется ошибка ниже

GET http://localhost:4200/api/getUsers 404 (не найдено) enter image description here Может кто-нибудь помочь мне решить эту проблему?

Пожалуйста, проверьте код моих трех файлов

1.proxy-config.json

2.user.service.ts

3.app-routing.module.ts


/*proxy-config.json*/
{
  "/api": {
  "target": "http://localhost:4200",
  "secure": false,
  "pathRewrite": {"^/api" : ""}
  }
}

/*user.service.ts*/
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { User } from './user';
import { USERS } from './mock-users';

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

@Injectable({
  providedIn: 'root'
})
export class UserService {
	
  private usersUrl = 'api/getUsers';  // URL to web api

  constructor(private http: HttpClient) { }

  /** GET users from the server */
  getUsers (): Observable<User[]> {
    return this.http.get<User[]>(this.usersUrl)
      .pipe(
        tap(users => this.log(`fetched users`)),
        catchError(this.handleError('getUsers', []))
      );
  }

  /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  /** Log a HeroService message with the MessageService */
  private log(message: string) {
    //this.messageService.add('HeroService: ' + message);
  }
  
}

/*app-routing.module.ts*/
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  {
    path: 'users',
    component: UsersComponent
  },    
];

@NgModule({
  imports: [RouterModule.forRoot(routes),
  			CommonModule
  			],
  exports: [RouterModule],
  declarations: []
})

export class AppRoutingModule { }

1 Ответ

0 голосов
/ 04 июля 2018

Угловое приложение по умолчанию работает на порте 4200, если вы явно не изменили его и не делаете запрос AJAX на том же порту http://localhost:4200/api/getUsers.

Полагаю, вы намереваетесь сделать HTTP-запрос на другом порту, где работает ваш сервер.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...