やりたいこと
Flutterアプリケーションで入力した値をphpで作成したAPIで受け取りたい。
現状と質問
Flutter作成したアプリケーションのログイン画面で入力した値を
JSON形式で送信し、
PHPで作成したAPIで受け取ろうとしています。
現状POST通信ができていることだけは確認できています。
(PHPからのレスポンスステータスコードを確認)
しかしリクエストの引数にいれたものが、
PHP側で受け取れていません。
その理由がわからないです。
発生している問題・エラーメッセージ
APIを側で起こっているエラーメッセージです。↓
Uncaught Error: Using $this when not in object context
こちらのエラー文は、CakePHPの書き方を、CakeではないPHPで書いているからだろうとは考えているのですが、
同じ動きをする別の書き方がわからないので、
別途わかれば教えていただきたいです。
(以下の部分です)
php
1$mail = $this->request->getData('mail_api') ?? null; 2$pass = $this->request->getData('pass_api') ?? null;
ソースコード
Flutter(送信側)
dart
1//APIへの接続 2//mailとpassを引数としてAPIへPOST送信するように作っています。 3 Future<void> accessAPI() async{ 4 var url = Uri.parse("http://***.***.**.**/loginAPI.php"); //パスは本来正しいものを入れています。 5 var request = new SampleRequest(mail_api: 'abcd', pass_api: 'efgh'); //仮の引数を送っています。 6 try{ 7 final response = await http.post(url, 8 body: json.encode(request.toJson()), 9 headers: {"Content-Type": "application/json"}); 10 if (response.statusCode == 200) { 11 print("#成功"); //「成功」が表示されるので、疎通確認は取れていると判断しています。 12 } else { 13 print(response.statusCode); 14 } 15 }catch(error){ 16 print(error); 17 print("接続失敗"); 18 } 19 } 20 21class SampleRequest { 22 final String? mail_api; 23 final String? pass_api; 24 SampleRequest({ 25 this.mail_api, 26 this.pass_api, 27 }); 28 Map<String, dynamic> toJson() => { 29 'mail_api': mail_api, 30 'pass_api': pass_api, 31 }; 32}
次にAPI側です。
php
1<?php 2// 文字コード設定 3header('Content-Type: application/json; charset=UTF-8'); 4$body = file_get_contents('php://input'); 5print "bodyの中身:".$body; //ここで中身を確認すると何も表示されません。 6$data = json_decode($body, true); 7print "dataの中身:".$data; //ここでも中身を確認すると何も表示されません。 8//$mail = $this->request->getData('mail_api') ?? null; 9//$pass = $this->request->getData('pass_api') ?? null; 10 11if (empty($mail)) { 12 $this->badRequest('mail is empty. This message from API.'); 13} 14$response = []; 15$response['mail'] = $mail; 16$response['message'] = 'api success. This message from API.'; 17$this->httpNormalResponse($response); 18 19?>
試したこと
私が参考にしているページを載せておきます。
https://qiita.com/kenichiro-yamato/items/12d7199cb2d7812ac0ce
https://qiita.com/YoshiakiOshima/items/40aac200b37fe98b9835
https://forsmile.jp/development/php/1709/
もしわかれば宜しくお願い致します。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。