Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Boot REST - Required String parameter is not present

So, I'm trying to to a POST request to a local Spring MVC project, but every time I try, I keep getting 400: Bad Request, with the error specified in the title. Not sure why, because when I check what's being sent, it's correct.

Spring REST controller request

@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);
}

AngularJS request sending the data

$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);
        });

front-end HTML that's calling the AngularJS function

<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>
like image 410
Brandon Hewlett Avatar asked Dec 06 '22 18:12

Brandon Hewlett


2 Answers

You are using @RequestParam in the backend but in angular you are putting the values in the body of the request.

You have to use @RequestBody in the backend or adjust the frontend to put the values in url parameters.

like image 166
niekname Avatar answered Dec 09 '22 13:12

niekname


Found the answer. I followed SSH's answer above for the front-end, and for the backend, I changed the function to:

void addPet(@RequestBody Pet pet)
like image 27
Brandon Hewlett Avatar answered Dec 09 '22 14:12

Brandon Hewlett