AngularアプリケーションからLaravelで作ったAPIに接続してDBのデータを取得したいのですが、うまくいきません。
●表示されるエラー
Chromeで試していますが、開発者ツールには下記のようなエラーが表示されます。
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://172.21.0.5:80/api/customers", ok: false, …}
message: "Http failure response for http://172.21.0.5:80/api/customers: 0 Unknown Error"
●前提条件
・AngularアプリもLaravelアプリもdocker環境で動いています。
・ローカルPCのブラウザのURL入力欄でAPIのURLを入力すると、ちゃんとほしい情報が返ってきます。
・Angularアプリが動いているnode.jsコンテナからcurlコマンドでAPIをたたくと、ちゃんとほしい情報が返ってきます。
・クロスドメインの対応はしてあります。
●各種ソースコード
html
1<!-- customer-list.component.html --> 2<button (click)="get()">get</button> 3<table > 4 <tr><th>Id</th><th>Name</th> 5 <tr *ngFor="let customer of customers"> 6 <td>{{customer.customer_number}}</td> 7 <td>{{customer.name}}</td> 8 </tr> 9</table> 10
typescript
1// customer-list.component.ts 2 3import { Component, OnInit } from "@angular/core"; 4import { CustomerService } from "../service/customer.service"; 5import { Customer } from "../shared/models/customer.model"; 6@Component({ 7 selector: "app-customer-list", 8 templateUrl: "./customer-list.component.html", 9 styleUrls: ["./customer-list.component.scss"] 10}) 11export class CustomerListComponent implements OnInit { 12 customers: Customer[]; 13 constructor(private cs: CustomerService) {} 14 15 ngOnInit(): void {} 16 17 get() { 18 this.cs.getCustomerList().subscribe(res => { 19 this.customers = res; 20 }); 21 } 22} 23
typescript
1// customer.service.ts 2import { Injectable } from "@angular/core"; 3import { Customer } from "../shared/models/customer.model"; 4import { HttpClient } from "@angular/common/http"; 5import { Observable } from "rxjs"; 6import { of } from "rxjs"; 7import { catchError } from "rxjs/operators"; 8@Injectable({ 9 providedIn: "root" 10}) 11export class CustomerService { 12 customers: Customer[]; 13 private url = "http://172.21.0.5:80/api/customers"; 14 15 constructor(private http: HttpClient) {} 16 17 getCustomerList(): Observable<Customer[]> { 18 return this.http 19 .get<Customer[]>(`${this.url}`) 20 .pipe(catchError(this.handleError("getCustomerList", []))); 21 } 22 23 private handleError<T>(operation = "operation", result?: T) { 24 return (error: any): Observable<T> => { 25 console.error(error); 26 console.log(`${operation} failed: ${error.message}`); 27 return of(result as T); 28 }; 29 } 30} 31
typescript
1//customer.model.ts 2export class Customer { 3 customer_number: string; 4 tel: string; 5 name: string; 6 name_kana: string; 7 address: string; 8 address_kana: string; 9 birthday: string; 10 sex: string; 11 debt: number; 12 point: number; 13} 14
typescript
1//app.module.ts 2import { BrowserModule } from '@angular/platform-browser'; 3import { NgModule } from '@angular/core'; 4 5import { AppRoutingModule } from './app-routing.module'; 6import { AppComponent } from './app.component'; 7import { CustomerListComponent } from './customer-list/customer-list.component'; 8 9import { HttpClientModule} from '@angular/common/http' 10 11@NgModule({ 12 declarations: [ 13 AppComponent, 14 CustomerListComponent 15 ], 16 imports: [ 17 BrowserModule, 18 AppRoutingModule, 19 HttpClientModule, 20 ], 21 providers: [], 22 bootstrap: [AppComponent] 23}) 24export class AppModule { } 25
クロスオリジンの対応は以下のようにしています。
php
1<?php 2 3namespace App\Http\Middleware; 4use Illuminate\Support\Facades\Log; 5use Closure; 6 7class Cors 8{ 9 /** 10 * Handle an incoming request. 11 * 12 * @param \Illuminate\Http\Request $request 13 * @param \Closure $next 14 * @return mixed 15 */ 16 public function handle($request, Closure $next) 17 { 18 $response = $next($request); 19 $http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ""; 20 21 if ($http_origin == "http://localhost:4200") { 22 $response 23 ->header("Access-Control-Allow-Origin" , $http_origin) 24 ->header("Access-Control-Allow-Headers" , 'content-type'); 25 } 26 27 return $response; 28 } 29} 30
php
1 2 3//省略 4protected $middleware = [ 5 \App\Http\Middleware\TrustProxies::class, 6 \App\Http\Middleware\Cors::class, //追加 7 \App\Http\Middleware\CheckForMaintenanceMode::class, 8 \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, 9 \App\Http\Middleware\TrimStrings::class, 10 \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, 11 ]; 12 13 /** 14 * The application's route middleware groups. 15 * 16 * @var array 17 */ 18 protected $middlewareGroups = [ 19 'web' => [ 20 \App\Http\Middleware\Cors::class, //追加 21 \App\Http\Middleware\EncryptCookies::class, 22 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 23 \Illuminate\Session\Middleware\StartSession::class, 24 \Illuminate\Session\Middleware\AuthenticateSession::class, 25 \Illuminate\View\Middleware\ShareErrorsFromSession::class, 26 \App\Http\Middleware\VerifyCsrfToken::class, 27 \Illuminate\Routing\Middleware\SubstituteBindings::class, 28 ], 29 30//省略
回答1件
あなたの回答
tips
プレビュー