2017-11-21 25 views
0

Sinatra (Mongodb)에 API가 있습니다. Angularjs로 작성된 매우 작은 응용 프로그램에서 POST 메서드로 일부 데이터를 쓰려고합니다. 내가 보내려고하는 데이터는 'aplication/x-www-form-urlencoded'입니다. 어떤 이유로 나는 오류가 계속 :Sinatra 오류 - JSON :: ParserError - 784 : 예기치 않은 토큰

JSON::ParserError - 784: unexpected token at 'id=111&name=Bruce&city=LA&address=City1': 

내가 URL로 인코딩 된 일부 데이터가 있음을 볼 수 있지만시나가 올바르게 읽지 않습니다.

시나 :

post '/companies' do 
    company=JSON.parse(request.body.read) 
    company = Company.new(company) 
end 

AngularJS와 스크립트

var formApp = angular.module('formApp', []); 
function formController($scope, $http) { 
    $scope.formData = {}; 
    $scope.processForm = function() { 
     $http({ 
      method : 'POST', 
      url  : 'http://localhost:4567/api/v1/companies', 
      data : $.param($scope.formData), // pass in data as strings 
      headers : { 'Content-Type': 'application/x-www-form-urlencoded' } 
     }) 
      .success(function(data) { 
       console.log(data); 
       if (!data.success) { 
        // if not successful, bind errors to error variables 
        $scope.errorName = data.errors.name; 
        $scope.errorSuperhero = data.errors.superheroAlias; 
       } else { 
        // if successful, bind success message to message 
        $scope.message = data.message; 
           $scope.errorName = ''; 
        $scope.errorSuperhero = ''; 
       } 
      }); 
    }; 
} 

형태가 HTML 완료 후 나는 버튼으로 기능 formData를 호출 오전 : 당신은 시도

body ng-app="formApp" ng-controller="formController"> 
<div class="container"> 
<div class="col-md-6 col-md-offset-3"> 

    <!-- PAGE TITLE --> 
    <div class="page-header"> 
     <h1><span class="glyphicon glyphicon-tower"></span> Submitting Forms with Angular</h1> 
    </div> 

    <!-- SHOW ERROR/SUCCESS MESSAGES --> 
    <div id="messages" class="well" ng-show="message">{{ message }}</div> 

    <!-- FORM --> 
    <form ng-submit="processForm()"> 


     <div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }"> 
      <label>ID</label> 
      <input type="text" name="id" class="form-control" placeholder="Caped Crusader" ng-model="formData.id"> 
      <span class="help-block" ng-show="errorSuperhero">{{ errorSuperhero }}</span> 
     </div> 


     <div id="name-group" class="form-group" ng-class="{ 'has-error' : errorName }"> 
      <label>Name</label> 
      <input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="formData.name"> 
         <span class="help-block" ng-show="errorName">{{ errorName }}</span> 
     </div> 

     <!-- SUPERHERO NAME --> 
     <div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }"> 
      <label>City</label> 
      <input type="text" name="city" class="form-control" placeholder="Caped Crusader" ng-model="formData.city"> 
      <span class="help-block" ng-show="errorSuperhero">{{ errorSuperhero }}</span> 
     </div> 

       <div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }"> 
      <label>Address</label> 
      <input type="text" name="address" class="form-control" placeholder="Caped Crusader" ng-model="formData.address"> 
      <span class="help-block" ng-show="errorSuperhero">{{ errorSuperhero }}</span> 
     </div> 

     <!-- SUBMIT BUTTON --> 
     <button type="submit" class="btn btn-success btn-lg btn-block"> 
      <span class="glyphicon glyphicon-flash"></span> Submit! 
     </button> 
    </form> 

    <!-- SHOW DATA FROM INPUTS AS THEY ARE BEING TYPED --> 
    <pre> 
     {{ formData }} 
    </pre> 

</div> 
+0

JSON을 구문 분석하려고하지만 해당 문자열이 JSON처럼 보이지 않습니다. 구문 분석하려는 문자열의 전체 문자열을 게시 할 수 있습니까? –

+0

나는 anglejs 스크립트 및 html 형식의 게시물을 편집했습니다. 다른 것을보고 싶다면 – quant

+0

이라고 말하십시오. AngularJS 코드는 오래되어 사용되지 않습니다. 자세한 내용은 [왜 $ $ 성공/오류 메서드가 더 이상 사용되지 않습니다? v1.6에서 삭제?] (https://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg

답변

0

AngularJS 코드가 URL 인코딩 형식으로 데이터를 보내므로 오류가 발생합니다. JSON 문자열로 데이터를 게시 :

var formApp = angular.module('formApp', []); 
function formController($scope, $http) { 
    $scope.formData = {}; 
    $scope.processForm = function() { 
     $http({ 
      method : 'POST', 
      url  : 'http://localhost:4567/api/v1/companies', 
      ̶d̶a̶t̶a̶ ̶ ̶ ̶ ̶:̶ ̶$̶.̶p̶a̶r̶a̶m̶(̶$̶s̶c̶o̶p̶e̶.̶f̶o̶r̶m̶D̶a̶t̶a̶)̶,̶ ̶ ̶/̶/̶ ̶p̶a̶s̶s̶ ̶i̶n̶ ̶d̶a̶t̶a̶ ̶a̶s̶ ̶s̶t̶r̶i̶n̶g̶s̶ 
      data : $scope.formData, //data automatically coded as JSON string 
      ̶h̶e̶a̶d̶e̶r̶s̶ ̶:̶ ̶{̶ ̶'̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶:̶ ̶'̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶x̶-̶w̶w̶w̶-̶f̶o̶r̶m̶-̶u̶r̶l̶e̶n̶c̶o̶d̶e̶d̶'̶ ̶}̶    
     }) 
      ̶.̶s̶u̶c̶c̶e̶s̶s̶(̶f̶u̶n̶c̶t̶i̶o̶n̶(̶d̶a̶t̶a̶)̶ ̶{̶ 
      .then(function(response) { 
       ̲v̲a̲r̲ ̲d̲a̲t̲a̲ ̲=̲ ̲r̲e̲s̲p̲o̲n̲s̲e̲.̲d̲a̲t̲a̲;̲ 
       console.log(data); 
       if (!data.success) { 
        // if not successful, bind errors to error variables 
        $scope.errorName = data.errors.name; 
        $scope.errorSuperhero = data.errors.superheroAlias; 
       } else { 
        // if successful, bind success message to message 
        $scope.message = data.message; 
           $scope.errorName = ''; 
        $scope.errorSuperhero = ''; 
       } 
      }); 
    }; 
} 

은 $ HTTP 서비스가 자동으로 JSON 문자열로 자바 스크립트 객체를 인코딩합니다. 콘텐츠 형식 헤더는 application/json으로 설정됩니다.

.success 방법은 사용되지 않습니다. 대신 .then을 사용하십시오. 자세한 내용은 Why are angular $http success/error methods deprecated? Removed from v1.6?을 참조하십시오.

+0

도움을 주셔서 감사합니다. 수정했지만 서버에 xhanges가 없으면 콘솔에 404 erroe가 표시됩니다. 그런 다음 헤더를 추가했는데 t200 OK가되었지만 응답 오류가 발생했습니다. SyntaxError : JSON.parse : JSON 데이터의 1 행 1 열의 데이터가 예기치 않게 끝난 다음 params 탭으로 바뀌 었습니다. {{ " id ":"99 ","name ":"Bruce Lee ","city ":"Shangai ","address ":"MStreet "} :! 나는이 이중 콜론을 볼 수있다, 나는 그것이 바로 오류의 이유라고 생각한다? – quant

+0

그것은 바로 대답으로 나를 이끌었습니다. 그래서이 대답을 받아 들였습니다. 도움을 주셔서 감사합니다. – quant

0

을 URL로 인코딩 된 데이터를 JSON 파서를 통해 전달하여 파싱합니다. 이것은 작동하지 않습니다.

response.body을 JSON 문자열이 아닌 일반 문자열로 파싱 해보십시오.