Vue.jsからaxiosを使用してPHPにPOSTしてPHPで受け取ったデータを出力したいです。
が、送信はできているっぽいのですが、送信している中身が想定通りの形ではないのと、phpでどのように受け取るのか。
現状、response.dataで返却されるのはこちら。
javascript
1送信したテキスト: <pre class='xdebug-var-dump' dir='ltr'> 2<small>/var/www/laradock/workspace/costa/create_project.php:29:</small> 3<b>array</b> <i>(size=2)</i> 4 'name' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'foo'</font> <i>(length=3)</i> 5 'surname' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'bar'</font> <i>(length=3)</i> 6</pre> 7model_project.vue?9760:51 {data: "<pre class='xdebug-var-dump' dir='ltr'>↵<small>/va…r='#cc0000'>'bar'</font> <i>(length=3)</i>↵</pre>", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
php側は、空です。
php
1array (size=0) 2 empty
App.vue
javascript
1s_project: function () { 2 // let params = new URLSearchParams() 3 // params.append('text', 'これはてせうと') 4 console.log('APIが叩かれた') 5 const hoge = this.message 6 console.log(hoge) 7 const params = new URLSearchParams() 8 params.append('event_id', {'hoge': 'testtest'}) 9 axios.post('http://hoge.lvh.me/api/hoge.php', {'name': 'foo', 'surname': 'bar'}, {headers: {'content-type': 'application/json'}}) 10 .then(response => { 11 console.log('送信したテキスト: ' + response.data) 12 console.log(response) 13 }) 14 .catch(e => { 15 // this.errors.push(e) 16 console.log('エラー!!!!!!!!') 17 }) 18 }
以下phpコードはほかの方のコードを参考にしたものです。
https://qiita.com/amamamaou/items/b6cb39739bba4abf4544
index.php
php
1<?php 2header("Access-Control-Allow-Origin: *"); 3header("Access-Control-Allow-Headers: *"); 4function get_request() { 5 $content_type = explode(';', trim(strtolower($_SERVER['CONTENT_TYPE']))); 6 $media_type = $content_type[0]; 7 8 if ($_SERVER['REQUEST_METHOD'] == 'POST' && $media_type == 'application/json') { 9 // application/json で送信されてきた場合の処理 10 $request = json_decode(file_get_contents('php://input'), true); 11 } else { 12 // application/x-www-form-urlencoded で送信されてきた場合の処理 13 // REQUESTのjsonが多層の時はうまく行かない 14 $request = $_REQUEST; 15 16 // REQUESTのjsonが多層の場合に対応 17 foreach ($_REQUEST as $key => $value) { 18 $request[$key] = json_decode($value, true); 19 20 // json_decodeはクォートされていない文字列がnullになるので戻す 21 if ($request[$key] == null) { 22 $request[$key] = $value; 23 } 24 } 25 } 26 return $request; 27} 28$hoge = get_request(); 29var_dump($hoge); 30
あなたの回答
tips
プレビュー