Post form data to rest resource in angularJS

I am trying to post form data as a request body to a rest service using angularJS but I cannot get it to hit the resource. Please help if you can..

I have a service like this ...

angular.
  module('core.search').
  factory('Search', ['$resource',
    function($resource) {
      return $resource('http://localhost:8888/PROJECT/rest/search, {}, {
          query: {
              method: 'POST',
              isArray: true
          }
      });
    }
  ]);

A component like this...

angular.
  module('vehicleSearch').
  component('vehicleSearch', {
    templateUrl: 'vehicle-search/vehicle-search.template.html',
    controller: ['Search',
      function VehicleSearchController(Search) {
        this.vehicles = [];
        this.searchVehicles = function(vehicleSearchForm) {
            this.vehicles = Search.query([], JSON.stringify(vehicleSearchForm));
        };
      }
    ]
  });

and a template like this ...

<div>
<h4>Vehicle Search</h4>
<form ng-submit="$ctrl.searchVehicles(vehicleSearchForm)">
    <table>
        <tr>
            <td><label for="vrm" >VRM: </label></td>
            <td><input type="text" id="vrm" name="vrm" ng-model="vehicleSearchForm.vrm" /></td>
            <td><input type="text" id="type" name="type" ng-model="vehicleSearchForm.type" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="search"/></td>
        </tr>
    </table>
    <br>
    <table>
        <tr>
            <td>VRM</td>
            <td>Make</td>
            <td>Model</td>
            <td>Colour</td>
            <td>Date Registered</td>
        </tr>
        <tr ng-repeat="vehicle in $ctrl.vehicles">
            <td>{{vehicle.vrm}}</td>
            <td>{{vehicle.make}}</td>
            <td>{{vehicle.model}}</td>
            <td>{{vehicle.colour}}</td>
            <td>{{vehicle.dateFirstReg}}</td>
        </tr>
    </table>
</form>

I know the resource is returning data as I can call it through my testing tool with a request body with media type application/json like .. {"type" : "vehicleSearchRequest", "searchReason" : "01", "vrm" : "ABC123"}

I thought maybe I needed to specify what media type the body would be but the default appears to be the same so am at a loss. When I try this in angular I can see the request is hitting the server as is authenticated but then does nothing so believe it is something to do with the request body. Please help.


I discovered that the problem was in fact due to my rest resources being on a different domain. The browser doesn't allow this for security reasons. The error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. For anybody who makes same mistake see: XMLHttpRequest cannot load https://www.[website].com/

链接地址: http://www.djcxy.com/p/77658.html

上一篇: 注入角度指令和服务。 [$ injector:unpr]错误

下一篇: 发布表单数据以在angularJS中休息资源