简体   繁体   中英

why http service in angularjs always error

I have some code below: app.js

app.controller("carCtrl", function($scope, $http, $window) {
  $scope.createTenCar = function() {
    $http({
      method: "POST",
      url: "http://localhost:8080/EX11_29112018_spring_restful/cars"
    }).then(function success(response) {
      alert('ok');

    }, function error(response, headers, config) {
      alert("fail");
      console.log(response);
    });
  };

file html

<ul class="dropdown-menu">
    <li><a href="#!car">show all car</a></li>
    <li><a href="#" ng-controller="carCtrl" ng-click = 
       "createTenCar()">create ten car</a></li>
 </ul>

function create car in java, it create a random car. It alway return message success and status 201 when I test on postman:

@RequestMapping(value = "/cars", method = RequestMethod.POST)
    public ResponseEntity<String> createTenCar() {
        String message = carSerVice.createTenCar();
        return new ResponseEntity<String>(message, HttpStatus.CREATED);
}

But when I run file html $http.post always jump to error function. Can some one help me. this is my screenshoot

This usually happens when bad data comes from your backend. Recommend you to check whether response in the backend is valid

I fixed it. method carSerVice.createTenCar() return a message like this "success". it is incorrect format to parse in JSON, I replace "success" by "\\"success\\"" and it work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM