Laravel请求转发至第三方url-日常笔记

需求:为了用mock自动生成的api做测试,且避免跨域问题,所以采取的策略是laravel将请求的api url做一次转发,转发至mock服务器。

一、插件

GuzzleHttp

安装方法

composer require guzzlehttp/guzzle:~6.0

二、使用方法

use GuzzleHttp\Client;
class yourController extends Controller {

    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);
        echo $res->getStatusCode();
        // "200"
        echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
        echo $res->getBody();
        // {"type":"User"...'
}

三、实例测试

Route::get('{path}',function ($path,Request $request) {
            $client = new GuzzleHttp\Client();
            $url = "http://apitest.work.tianheng-uestc.com/mock/59acc125236ef903579a282c/".$path;
            $res = $client->request('GET',$url);
            // echo $res->getStatusCode();
            // "200"
            // 'application/json; charset=utf8'
           // echo $url;
           // echo $res->getBody();
            return response()->json(json_decode($res->getBody()));
            return ;

        })->where('path', '.+');

 

分享到:更多 ()