質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Angular

Angularは、JavaScriptフレームワークです。AngularJSの後継であり、TypeScriptベースで実装されています。機能ごとに実装を分けやすく、コードの見通しが良いコンポーネント指向です。

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Docker

Dockerは、Docker社が開発したオープンソースのコンテナー管理ソフトウェアの1つです

Q&A

解決済

1回答

3363閲覧

AngularからLaravelのAPIをたたく

dev3310

総合スコア24

Angular

Angularは、JavaScriptフレームワークです。AngularJSの後継であり、TypeScriptベースで実装されています。機能ごとに実装を分けやすく、コードの見通しが良いコンポーネント指向です。

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Docker

Dockerは、Docker社が開発したオープンソースのコンテナー管理ソフトウェアの1つです

0グッド

0クリップ

投稿2020/03/10 06:02

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//省略

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

miyabi_takatsuk

2020/03/10 07:33

まず、 export class Customerは、クラス的な使い方をしていないので、 interfaceにした方がいいかと。 export interface Customer とするということです。 (初期化してないし、静的に使っているわけでもないため) もう一点、メソッド名に"get"を使うのはやめましょう。 ゲッター定義のgetキーワードと被るので。 (もしかしたら、それで直ったり?) ふむ・・・。特に問題なさそうですが、動きませんか・・・。
keisukeh

2020/03/29 14:19

両方Dockerで立ち上げてるのであればDocker内のネットワークの設定がうまくいってないのではないでしょうか?
guest

回答1

0

自己解決

APIのURLを
172.21.0.5⇒localhost
へ変更したら通りました。
docker-composeのymlファイルにネットワーク設定もしたし、curlではIPアドレスでちゃんと通信できていたので大丈夫かと思ったのですが、localhostのブラウザから叩いているからなのかなと考えています。
もう少し調査をしますが、一旦問題は解決しましたのでクローズさせていただきます。

投稿2020/04/01 00:32

dev3310

総合スコア24

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問