最近做了一個前端是vue+後臺springboot的項目,採用前後端分離的方式,用json傳值。
當我後端採用
@PostMapping(value = "/getSortWithFiveNews")
public Result getSortWithFiveNews(@RequestParam("sid")Long sid){
return sortService.getSortWithFiveNews(sid);
}
前端傳值採用axios
toSortNews()
{
this.$axios
.post("/getSortWithFiveNews",{
'sid':1
})
.then(successResponse => {
// console.log(successResponse)
})
.catch(failResponse => {
})
},
用這種方式傳值 後臺會報錯,爲什麼,因爲axios默認的請求頭是contentType 爲 application/x-www-form-urlencoded
這種默認是後臺用實體類或者一個map來接受參數
這種時候只有使用@RequestBody
對,它默認是這麼一種方式。
我們如果非得使用@RequestParam()也不是不行
這個時候我們得把請求頭改一下,改成
contentType不爲application/x-www-form-urlencoded
這裏我提供一種常用的方法
//得到某個分類的前五個新聞
getSortWithFiveNews(sid)
{
//使用URLSearchParams來傳遞參數
let param=new URLSearchParams();
param.append('sid',sid)
this.$axios
.post("/getSortWithFiveNews",param)
.then(successResponse => {
console.log(successResponse)
})
.catch(failResponse => {
})
},
完事。