Currently I have an axios post request that works fine for sending the data to Spring Boot backend. But it just wraps single list of data to json and sends it as requested body:
Example:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
}).then(response=> console.log("repsonse", response.status)) // is 201
}
And it receives it on backend:
@RequestMapping(path = "/receiveData", method = RequestMethod.POST)
public ResponseEntity<Void> receiveData(@RequestBody Collection<ActivePOJO> activitePOJOS) {
//DO WORK WITH activePOJOS DATA
return new ResponseEntity<>(HttpStatus.CREATED);
}
However, apart from that information, I also need to send some other info like user.id (as example), so I need my backend to receive something like this:
public ResponseEntity<Void> receiveData(@RequestBody Collection<ActivitePOJO> activePOJOS, Long userID)
But I don't know which way should I prepare axios post for something like that. Should I use params instead of body?
You can use params and body together in a request with axios. To send userID as a param:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { userID: 1 }, //Add userID as a param
}).then(response=> console.log("repsonse", response.status)) // is 201
And receive userID in controller with @RequestParam
annotation:
public ResponseEntity<Void> receiveData(@RequestBody Collection<ActivitePOJO> activePOJOS, @RequestParam("userID") Long userID){
// here you can access userID value sent from axios
}
The third parameter is config and you can pass params to it along with header as a separate key. Refer this. https://github.com/axios/axios#axiosposturl-data-config
sendAllData(data) {
return axios
.post(API_URL + 'receiveData', JSON.stringify(data), {
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
params: { userId: 2 },
})
.then((response) => console.log('response', response.status));
} // is 201
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.