2016-06-07 101 views
0

我對AngularJS和Laravel 5.2感到沮喪。

我想做一個正常的$ HTTP POST請求:

APIservice.saveArticle = function (oArticle, callback) 
{ 
    var message = 'Hello World!'; 
    $http({ 
      method: 'POST', 
      url: sBaseUrl + '/api/dummy/', 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
      data: $.param({ 'message' : message }) 
    }); 
} 

如果我現在嘗試調用郵遞員這條路線(POST + URL/API /管理員),我可以根據標籤頭看到,內容類型是text/html。

所以我編輯的模塊配置:

artikelportal.config(
[ 
    '$httpProvider', 
    function($httpProvider) 
    { 
     $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; 
    } 
]); 

這仍然無法工作。而我的後端控制器也得不到數據:

Route::post('api/dummy', 
function (Request $request) 
{ 
    var_dump(json_decode(file_get_contents('php://input'), true)); // NULL 
    var_dump($_POST); // EMPTY 
} 
); 

我在做什麼錯了?我嘗試了這麼多,但我從來沒有這樣做......有人知道有什麼問題嗎?

+0

消息來自哪裏?你的意思是oArticle?我會避免像這樣混入jQuery,這可能是問題所在。嘗試將數據設置爲靜態,以確保您首先發回數據。 – Brian

+0

@BrianS我已經嘗試了這麼多,並與:http://kopy.io/qxAt8 和消息來自$ http({... – Gohan

+0

你在相同的域或不同的運行PHP和角度域? –

回答

2

郵差是一個休息客戶端。您需要設置請求標頭Content-type:application/x-www-form-urlencoded,以便將包含此標頭的請求發送到服務器。如果你沒有在請求中設置任何頭文件,郵差發送默認頭Content-type:text/html。這個例子在我的locahost中有效。

測試so.html

<!DOCTYPE html> 
<html ng-app="myApp"> 
    <head> 
     <title>Test Angular POST request</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
     <script src="app.js"></script> 
    </head> 
    <body ng-controller="testCtrl"> 
     <p>Press button and get response from the server</p> 
     <button ng-click="callServer()">Call</button> 
     <p><strong>Response:</strong></p> 
     <p>{{htmlResponse}}</p> 
    </body> 
</html> 

app.js

'use strict' 
var appModule = angular.module('myApp',[]).service('testService',['$http',function($http){ 
     this.getResponse = function(){ 
      return $http({ 
       url: "api-post.php", 
       method: "POST", 
       data: "p1=first_parameter&p2=second_parameter", 
       headers: {      
        "Content-Type": "application/x-www-form-urlencoded" 
       } 
      }); 
     } 
}]).controller('testCtrl',['$scope','testService',function($scope,testService){ 
    $scope.callServer = function(){ 
     testService.getResponse().then(function(response){ 
     $scope.htmlResponse = response.data; 
    }); 
    }; 

}]); 

API-post.php中

<?php 
echo "This text come from the server. You sent to me this:"; 
print_r($_POST); 
?> 

如果你單擊該按鈕的結果是這樣的: enter image description here

您可以在圖片中的Chrome Inspector工具中查看請求和響應。 這個例子適用於我的本地環境。 如果客戶端和服務器位於不同的域中,則存在安全限制(請參閱CORS)。