2016-05-20 20 views
0

我正在使用Silex創建一個RESTful API。要測試我正在使用Chrome的「簡單REST客戶端」插件。在Silex RESTful API中獲取POST正文數據

在插件我的URL設置爲:http://localhost/api-test/web/v1/clients 我設置的「方法」:帖子 我離開這個「頭」空白 我設置的「數據」到:名稱=無論

在我「clients.php」的網頁我有:

require_once __DIR__.'/../../vendor/autoload.php'; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 

$app = new Silex\Application(); 

$app->post('/clients', function (Request $request) use ($app) { 
    return new Response('Created client with name: ' . $request->request->get('name'), 201); 
} 

在插件中,輸出顯示:「狀態:201」(正確的),一系列的頭,和「數據:創建客戶端名稱:」(它應該說「數據:創建客戶名稱:不管」

我在做什麼錯?我也試過:$ request-> get('name')

謝謝。

+0

確保發送Content-Type頭與您的請求(即'Content-Type:application/x-www-form-urlencoded')。 – xabbuh

+0

@xabbuh我沒有創建表單,我正在創建一個API。這仍然是必要的嗎? –

+0

@xabbuh添加你的頭文件對我提供的「數據」有效,謝謝。我的Ember.js前端實際上是提交JSON,所以發佈的「數據」更可能是:{「name」:「whatever」},但是當我使用這些數據和標題「Content-Type:application/json「或」Content-Type:application/vnd.api + json「,它不輸出名稱。 –

回答

2
需要有

三個步驟來解決:

1)在 「簡單的REST客戶端」 的 「頁眉」 設置:

Content-Type: application/json 

2)將 「數據」 到:

{ "name": "whatever" } 

3)在Silex的代碼添加到輸入轉換爲JSON,如在http://silex.sensiolabs.org/doc/cookbook/json_request_body.html描述:

$app->before(function (Request $request) { 
    if (strpos($request->headers->get('Content-Type'), 'application/json') === 0) { 
     $data = json_decode($request->getContent(), true); 
     $request->request->replace(is_array($data) ? $data : array()); 
    } 
}); 

然後,我能夠與訪問我的PHP代碼中的數據:

$request->request->get('name') 

謝謝@xabbuh的幫助,這使我對答案。

+1

你應該使用: 返回新的JsonResponse(array('1','a')); – fucethebads