Spring-Boot REST - 不存在必需的String参数

Bra*_*ett 3 java spring spring-mvc angularjs spring-boot

所以,我正在尝试向本地Spring MVC项目发出POST请求,但每次尝试时,我都会收到400:Bad Request,标题中指定了错误.不知道为什么,因为当我检查发送的是什么时,它是正确的.

Spring REST控制器请求

@RequestMapping(value="/add", method = RequestMethod.POST)
void addPet(@RequestParam String name, @RequestParam String photo, @RequestParam String status) {
    Pet pet = new Pet(name, photo, status);
    this.petRepo.save(pet);
}
Run Code Online (Sandbox Code Playgroud)

AngularJS请求发送数据

$http({
       method: "post",
       url: "http://localhost:8080/pet/add",
       data:{
           name: angular.element("#name")[0].value,
           photo: angular.element("#photo")[0].value,
           status: angular.element("#status")[0].value
       }
    }).success(function(data, status) {

        })
        .error(function(data, status) {
            alert("Error");
            console.log(data);
            console.log(status);
        });
Run Code Online (Sandbox Code Playgroud)

调用AngularJS函数的前端HTML

<div class="form-group">
        <label for="name">Pet Name</label>
        <input type="text" class="form-control" id="name">
    </div>
    <div class="form-group">
        <label for="photo">Photo URL</label>
        <input type="text" class="form-control" id="photo">
    </div>
    <div class="form-group">
        <label for="status">Status</label>
        <input type="text" class="form-control" id="status" placeholder="Something descriptive like 'Available' or 'Taken'">
    </div>
    <div class="form-group">
        <div class="btn-group">
            <button type="button" class="btn btn-primary" ng-click="preview()">Preview</button>
            <button type="button" class="btn btn-success" ng-click="submit()">Submit</button>
            <button type="button" class="btn btn-danger" ng-click="clear()">Clear</button>
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

nie*_*ame 9

您在后端使用@RequestParam但是在角度中您将值放在请求的正文中.

您必须在后端使用@RequestBody或调整前端以将值放入url参数中.