使用 AngularJS 提出请求

Make requests with AngularJS

我今天从 AngularJS 开始,我尝试用 AngularJS 向我的 API 发送 post,但我什么也没收到,甚至没有错误 500单击按钮时的代码。
我的请求有什么问题?

API

@Controller
@RequestMapping("/veiculo")
public class VeiculoAPI {

    @RequestMapping(value = "/novo/{nome}", method = RequestMethod.POST)
    public void novoVeiculo(@Param("nome") String nome) {
        System.out.println("Veículo : " + nome);
    }

}

HTML

<!DOCTYPE html>
<html ng-app="oknok">
<script>
    function salvar($scope) {
        var nomeVeiculo = $scope.veiculo;
        $http.post("/veiculo/novo/", {"veiculo" : "nomeVeiculo"})
    .success(function (data, status, headers, config) {
            $scope.data = data;
        }).error(function (data, status, headers, config) {
            $scope.status = status;
        })
    }
</script>
<head lang="en">
    <meta charset="UTF-8"/>
    <title>OKNOK Admin</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
</head>
<body ng-controller="formulario">

<center>
    <label>Veículo</label>
    <input type="text" ng-model="veiculo"/>
    <button ng-click="salvar()">Salvar</button>
</center>
</body>
</html>

要使用 angularJS 向任何 API 发出 HTTP 请求,您需要执行以下步骤:

  1. 创建控制器文件并在其中创建控制器
  2. 在控制器文件中创建一个 angular 模块
  3. 在控制器中创建 HTTP 请求

创建一个 controller.js 文件然后创建一个 angular 模块见下面的代码:

  //Within your controller.js file 
    var myApp = angular.module('myApp', []);
    myApp.controller('myController', function($scope, $http){

 // Create a function within the scope of the module
 $scope.makeRequest = function(){

    // Simple POST request example (passing data) :
    $http.post("API url here", {

         //Enter Request data in here, this is the data you want to pass to the API
         msg:"Hello World",
         name: "John Smith",
         gender: "Male"
    }).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available

    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });
};
});

然后在您的 HTML 文件中调用函数 on-Click 查看下面的代码:

注意:不要忘记将您创建的控制器添加到您的 HTML 代码中。我一般都加在body标签里

 <body ng-controller="myController">
    <button ng-click="makeRequest()">Make Request Button</button>
 </body>

要发出 GET 请求,请参阅以下代码:

  // Simple GET request example :
  $http.get('/someUrl').
    success(function(data, status, headers, config) {
  // this callback will be called asynchronously
 // when the response is available
 }).
   error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
   // or server returns response with an error status.
 });

希望对您有所帮助。