2016-06-07 7 views
0

저는 AngularJS와 Laravel 5.2를 좌절 시켰습니다.

내가 가진 정상 $의 HTTP POST 요청하고 싶지 : 지금 내가 탭 헤더에서 볼 수있는이 우편 배달부의 경로 (POST + URL/API/관리자)를 호출하려고하면

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 }) 
    }); 
} 

을 그 content-type은 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와 angular를 실행합니까? 도메인? –

답변

2

우편 배달부는 휴식 클라이언트입니다. 이 헤더가있는 요청을 서버에 보내려면 요청 헤더 Content-type : application/x-www-form-urlencoded를 설정해야합니다. 요청에 헤더를 설정하지 않으면 Postman은 기본 헤더 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> 

당신이 버튼을 클릭하면

'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); 
?> 

는 결과가 이것이다 app.js : enter image description here

이미지의 Chrome Inspector 도구에서 요청 및 응답을 볼 수 있습니다. 이 예제는 내 로컬 envirovment에서 작동합니다. 클라이언트와 서버가 다른 도메인에있는 경우 보안 제한이 있습니다 (CORS 참조).

관련 문제