简体   繁体   中英

How to send data to spring boot method using FETCH API

I am exploring fetch api and want to send some for date to a spring boot method, but it is throwing 400 error

JS code

let fetchConfig = {
            method : params.method || 'GET',
            body : params.body
        };
        return fetch(_url,fetchConfig).then(function (response) {
            if (!response.ok) {
                throw Error(response.statusText);
            }
            else {
                return response.json();
            }
        }).then(function (data) {
            return data;
        }).catch(function (error) {
            return error;
        })

Spring boot method

@RequestMapping(value = "/validate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public  @ResponseBody ValidateUserModel validateUser(@RequestParam("userName") String userName, @RequestParam("password") String pass){
        System.out.println("--- test");
        ValidateUserModel validateUserModel = new ValidateUserModel();
        validateUserModel.setUserName("Test");
        validateUserModel.setPassWord("Test 2");
        return  validateUserModel;
    }

This is how fetchConfig looks like

body:{userName: "awdaw", password: "awdawd"}
method:"POST"
password:"test"
url:"test"
userName:"awdaw"
__proto__:Object

Preview of the values send from java class

error:"Bad Request"
exception:"org.springframework.web.bind.MissingServletRequestParameterException"
message:"Required String parameter 'userName' is not present"
path:"/validate"
status:400
timestamp:1504771336175

The error says Required String parameter 'userName' is not present but the fetchConfig have the required key

Your Java code expects request params, so the expected url should be something like .../validate?username=<someValue>&password=<otherValue> , but your js is sending that in the body (which is a better option, sending user and password as part of the URL is not secure at all).

You could change your Java code to something like

@RequestMapping(value = "/validate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public  @ResponseBody ValidateUserModel validateUser(@RequestBody User user){
    System.out.println("--- test");
    ValidateUserModel validateUserModel = new ValidateUserModel();
    validateUserModel.setUserName(user.getUserName());
    validateUserModel.setPassWord(user.getPassword());
    return validateUserModel;
}

Where User is just a bean with password and userName as attributes.

Try Using @RequestBody annotation.

@RequestMapping(value = "/validate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public  @ResponseBody ValidateUserModel validateUser(@RequestBody User user){
    System.out.println("--- test");
    ValidateUserModel validateUserModel = new ValidateUserModel();
    validateUserModel.setUserName(user.getUserName());
    validateUserModel.setPassWord(user.getPassword());
    return validateUserModel;
}

and the request should look like:

  let data = {userName: "awdaw", password: "awdawd"};
    fetch{ url, {
      body: JSON.stringfy(data)
      method:"POST"
      headers: {
               "Content-Type": "application/json",
           },
     }).then(
            response =>  {
                return response.json();
            }

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