最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Spring Boot REST - Required String parameter is not present - Stack Overflow

programmeradmin1浏览0评论

I have trouble with sending data to Spring Boot server. I check with Postman, everything is good, but I use axios library of ReactJS, i get error

Required String parameter 'name' is not present.

addProduct funtion

addProduct = (e) => {
 e.preventDefault();
    var { productName, productPrice, productStatus } = this.state;
    callApi('product/add', 'POST', {
        name: productName,
        price: productPrice,
        status: productStatus
    }).then(res => {
        console.log(res);
    });
}

productController.java

@RestController
@RequestMapping(path = "/api/product")
public class ProductController {
    @Autowired
    private ProductRespository productRespository;

    @GetMapping(path = "/all")
    public @ResponseBody Iterable<Product> getAllProduct(){
        return productRespository.findAll();
    }

    @PostMapping(path = "/add")
    @ResponseBody
    public String createProduct(@RequestParam String name, @RequestParam Integer price, @RequestParam String status){
        Product product = new Product();
        product.setName(name);
        product.setPrice(price);
        product.setStatus(status);
        productRespository.save(product);
        return "OK";
    }
}

apiCaller.js

import axios from 'axios';
import * as Config from './../constants/Config';

export default function callApi(endpoint, method, body) {
    return axios({
        method: method,
        url: `http://localhost:8000/api/${endpoint}`,
        data: body,
        headers: {
            'Access-Control-Allow-Origin': '*' 
        }
    }).catch(err => {
        console.log(err);
    });
}

how can I solve?

I have trouble with sending data to Spring Boot server. I check with Postman, everything is good, but I use axios library of ReactJS, i get error

Required String parameter 'name' is not present.

addProduct funtion

addProduct = (e) => {
 e.preventDefault();
    var { productName, productPrice, productStatus } = this.state;
    callApi('product/add', 'POST', {
        name: productName,
        price: productPrice,
        status: productStatus
    }).then(res => {
        console.log(res);
    });
}

productController.java

@RestController
@RequestMapping(path = "/api/product")
public class ProductController {
    @Autowired
    private ProductRespository productRespository;

    @GetMapping(path = "/all")
    public @ResponseBody Iterable<Product> getAllProduct(){
        return productRespository.findAll();
    }

    @PostMapping(path = "/add")
    @ResponseBody
    public String createProduct(@RequestParam String name, @RequestParam Integer price, @RequestParam String status){
        Product product = new Product();
        product.setName(name);
        product.setPrice(price);
        product.setStatus(status);
        productRespository.save(product);
        return "OK";
    }
}

apiCaller.js

import axios from 'axios';
import * as Config from './../constants/Config';

export default function callApi(endpoint, method, body) {
    return axios({
        method: method,
        url: `http://localhost:8000/api/${endpoint}`,
        data: body,
        headers: {
            'Access-Control-Allow-Origin': '*' 
        }
    }).catch(err => {
        console.log(err);
    });
}

how can I solve?

Share Improve this question edited Aug 23, 2019 at 9:53 Huy Vu The asked Aug 23, 2019 at 9:32 Huy Vu TheHuy Vu The 1412 gold badges2 silver badges13 bronze badges 9
  • Append name in requested URL like 'product/add?name='+productName – Sudhir Ojha Commented Aug 23, 2019 at 9:36
  • how does your RESTController method look like? – Simon Martinelli Commented Aug 23, 2019 at 9:38
  • Where do you get that error? How is defined your request on server side? It may be good to show also callApi – barbsan Commented Aug 23, 2019 at 9:38
  • I get that error from server. I user axios to send request to server. – Huy Vu The Commented Aug 23, 2019 at 9:44
  • Does changing @RequestParam to @RequestBody in all createProduct params solve your issue? – barbsan Commented Aug 23, 2019 at 9:45
 |  Show 4 more comments

4 Answers 4

Reset to default 8

Your rest service expects name, price, status as request parameters and in spring these are mandatory by default. But in your react code you are not sending these as request parameters, instead you are sending them as request body.

As name is the first param as soon as it's not available spring throws 'name' not available exception, but once you fix it it will throw for price and then status. So fix them all together.

You have to either change your controller method like below, which will be more code efficient and rest standard way.

@PostMapping(path = "/add")
@ResponseBody
public String createProduct(@RequestBody Product product){
    productRespository.save(product);
    return "OK";
}

OR change your react code to send them in the request like below. But for 'POST' methods this is not recommended. Because this will reveal the information passed in url itself.

addProduct = (e) => {
    e.preventDefault();
    var { productName, productPrice, productStatus } = this.state;
    callApi('product/add?name=' + productName +  '&price=' + productPrice + '&status=' + productStatus , 'POST', {}).then(res => {
        console.log(res);
    });
}

The @RequestParam annotation gets its data from the url. Which should be like:

?name=myname&price=100&status=ok

The @RequestBody annotation is what you are looking for if you are sending the data as a json object in the body of the request. Make sure you also set the Content-Type in your axios request to application/json

axios.post('url', JSON.stringify({
        "name": productName,
        "price": productPrice,
        "status": productStatus,
     }) , { headers: {  "Content-Type": "application/json"  }
})

you either need to change the parameters of your add method to a single @RequestBody Product parameter. Or you should include all the parameters as query parameter in your Axios request ex: product/add?name=myname&price=100&status=ok

I was using wrong HTTP method. expected was POST and I was trying GET method

发布评论

评论列表(0)

  1. 暂无评论