I am trying to write a search function, but I encounter a bug when I pass the search query from frontend to backend. I tried most of the solution on Internet but it's still not ok.
Complete Error log
2022-10-12 15:05:10.575 WARN 21272 --- [nio-8090-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'searchQuery' for method parameter type String is not present]
frontend
<template>
<div >
<input type="search" v-model="searchQuery" placeholder="Company name" aria-label="Search" aria-describedby="search-addon" />
<button type="button" @click='searchRecord'>Search</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'RegistrationEnquiry',
components: {
},
data() {
return {
records: [],
searchQuery: '',
};
},
computed: {},
methods: {
searchRecord(){
axios.post('searchRecord', this.searchQuery)
.then(successResponse => {
console.log(successResponse)
})
.catch(failResponse => {
alert("Error(failResponse)")
console.log(failResponse)
})
},
},
}
</script>
SearchRecordController.java
@Controller
public class SearchRecordController {
@Autowired
SearchRecordService searchRecordService;
@CrossOrigin
@PostMapping(value = "api/searchRecord")
@ResponseBody
public String searchRecord(@RequestParam(value = "searchQuery") String searchQuery) {
System.out.println(searchQuery);
return searchRecordService.searchRecordService(searchQuery);
}
}
CodePudding user response:
It is not the correct way of sending parameters through axios. You can send params by changing your code in frontend to :-
axios.post(`api/searchRecord`, null, { params: {
searchQuery
}}
Which will send the request as : https://localhost:8080/api/searchRecord?searchQuery=valueofsearchtext
Keep your controller as it is as there are no changes required in the backend.
@CrossOrigin
@PostMapping(value = "api/searchRecord")
@ResponseBody
public String searchRecord(@RequestParam(value = "searchQuery") String searchQuery) {
System.out.println(searchQuery);
return searchRecordService.searchRecordService(searchQuery);
}
this should sort the issue in your code.
CodePudding user response:
From backend side it seems ok, I think you need to send data in post like that:
searchRecord(){
axios.post({
method: 'post',
url: '/api/searchRecord',
data: {
searchQuery: this.searchQuery
}
})
.then(successResponse => {
console.log(successResponse)
})
.catch(failResponse => {
alert("Error(failResponse)")
console.log(failResponse)
})
}
CodePudding user response:
Front end is not sending data to the controller. Try giving default value=null;