2016-02-18 44 views
0

我使用Laravel 5.2構建了一個RESTful API,並且我有一個AngularJS 1.5前端。我成功地編寫了服務以獲取信息,但是當我將它傳遞給API時,我正忙於將任何內容放入或發佈到數據庫中。我試着做一些搜索,但我只是不明白如何實際保存數據,我會發送API。這裏是我的嘗試至今:如何從角度前端向laravel API發送請求?

從出廠時

addReceipt: function(request) { 
      return $http.post(api_url + "/rewards/receipts/add", request).then(function(results) { 
       console.log(results); 
       return results.data; 
      }); 
     } 

- 從控制器

$scope.submitReceipt = function() { 
       rewardsFactory.addReceipt($scope.model).then(function() { 
        console.log($scope.model); 
        toaster.pop({ type: 'success', title: 'Claim Submitted!', body: "Thanks! We'll take a look at your claim shortly.", showCloseButton: true }); 
       }); 
      }; 

- 從Laravel API路線

Route::post('rewards/receipts/add', 'Rewards\[email protected]'); 

- 從Laravel - 服務控制器

public function addReceipt(Request $request) 
    { 
     //Add the Receipt 
     DB::table('receipts')->insert(
      ['transaction_id' => $request->input('transactionID'), 
      'client_id' => $request->input('client_id'), 
      'location_id' => $request->input('location_id') ] 
     ); 
    } 

我目前的Cors設置似乎工作得很好,至少有一些流量,所以我不認爲這是問題,但我仍然不確定我做錯了什麼。

+0

您是否知道故障在哪裏?如有疑問,請記錄日誌,日誌。 – aynber

+0

你的前端是否有Laravel安全令牌?這讓我的最後一次Laravel API生產了相當長的一段時間。 – mopsyd

+0

\ Log :: info($ request)在控制器中查看您的請求數據是否到達控制器。請記住在 – oseintow

回答

1

請注意,$http默認情況下不發送表單編碼數據,它在請求正文中發送application/json

我沒有和laravel做任何工作,但是如果你檢查$_POST你會看到它是空的,所以$request->input也可能是空的。

在PHP中可以使用訪問響應正文:

json_decode(file_get_contents('php://input')[,true/*optional to convert to array*/]) 

我相信json_decode($request->getContent())會做同樣的laravel

另一種方法是使用下面的$http設置從文檔送往發送格式編碼的數據

.controller(function($http, $httpParamSerializerJQLike) { 
    //... 

    $http({ 
    url: myUrl, 
    method: 'POST', 
    data: $httpParamSerializerJQLike(myData), 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
    } 
    }); 

}); 

您還可以設置$http.defaults在運行塊,所有職位或p ut發送爲x-www-form-urlencoded,並且不必爲每個用戶添加配置