Send request from javascript to Spring boot controller

Viewed 54

I am trying to make some calculations on server side using spring boot I want to send request with the required parameters needed by the controller function but it arises state 400 bad request. I am new to spring boot so I don’t even know if I doing it right. so to go straight, my purpose is sending Get request with the needed parameters of the spring controller function. so that for these parameters to be processed and return the result.

Note: it seems that the parameters aren't sent correctly and this warning arises on running in intellij. [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'first_operand' for method parameter type String is not present]

spring boot controller code

package Hyperion.Mostafa_Galal.Calculator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins="http://localhost:8080/")
@RequestMapping("/workout")
public class CalculatorController {
    private final CalcalutorService calcalutorService;

    @Autowired
    public CalculatorController(CalcalutorService calcalutorService) {
        this.calcalutorService = calcalutorService;
    }

    @GetMapping("/expression")
    public String calc(@RequestParam String first_operand, @RequestParam String operator, @RequestParam String second_operand) {
        return calcalutorService.workout(first_operand, operator, second_operand);
    }
}

javascript code

var xhr = new XMLHttpRequest();
            xhr.open("GET", "http://localhost:8080/workout/expression");
            
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
            
xhr.onload = () => console.log(xhr.responseText);
            
var data = {"first_operand": String(first_val), 
            "operator": String(operator),
            "second_operand": String(second_val)};

Thanks in advance

1 Answers

If you use method GET on spring, you must pass param to url when call xhr like:

var data = {
    "first_operand": String(first_val),
    "operator": String(operator),
    "second_operand": String(second_val)
};

var url = "http://localhost:8080/workout/expression";
if(data) url =  url + '?' + Object.keys(data).map(function (key) { return [key, data[key]].map(encodeURIComponent).join("="); }).join("&");

var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // do something
    }
};
            
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.open("GET", url, true);
xhttp.send();

Or if you don't want to pass param to url, you can use @RequestBody on spring server.

First: create class to mapping requestbody to class

public class DataForm {
    private String first_operand;
    private String operator;
    private String second_operand;

    // getter & setter
}

Second: change api to method POST like this:

@RequestMapping(value = "/expression", method = RequestMethod.POST)
public String calc(@RequestBody DataForm data) {
    return calcalutorService.workout(data.first_operand, data.operator, data.second_operand);
}

And call xhr like this:

var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // do something
    }
};
            
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.open("POST", "http://localhost:8080/workout/expression", true);
xhttp.send(data);

Hope this help!

Related