太久沒寫前后端傳遞參數(shù)了,總是格式對(duì)不上號(hào)
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、接收參數(shù)注解 @PathVariable
拼接在 url 地址中的
請(qǐng)求 url 如 : http://localhost:8001/eduservice/edu-teacher/1/3
這里的 1/3 這兩個(gè)都是傳遞的參數(shù)
后端
@PostMapping("{page}/{limit}")
@ApiOperation("條件分頁查詢講師")
public R pageWithConditions(@ApiParam(name = "page", value = "頁碼", required = true)
@PathVariable Integer page,
@ApiParam(name = "limit", value = "記錄條數(shù)", required = true)
@PathVariable Integer limit) {}
前端api
export function list(page, limit, searchObj) {
return request({
url: `/eduservice/edu-teacher/${page}/${limit}`, // 這里的 page / limit 就是拼接到 url 當(dāng)中的參數(shù)
method: 'post'
})
}
調(diào)用請(qǐng)求
eduTeacherAPI
.list(this.pageObj.pageNo, this.pageObj.pageSize)
.then(res => {})
二、接收參數(shù)注解 @RequestParam
2.1 get 請(qǐng)求,普通類型參數(shù)
拼接在 url 地址后面的
請(qǐng)求 url 如 : http://localhost:8001/eduservice/edu-teacher/test?name=testName
這里的 name=testName 是傳遞的參數(shù)
后端
@GetMapping("/test")
public R TestParam(@ApiParam(name = "id", value = "查詢講師id", required = true) @RequestParam String name) {
System.out.println(name);
return R.ok();
}
前端api
export function testParam(name) {
return request({
url: '/eduservice/edu-teacher/test?name=' + name,
method: 'get'
})
}
調(diào)用請(qǐng)求
const b = 'testName'
eduTeacherAPI.testParam(b).then(res => {
console.log(res)
})
2.2 post 請(qǐng)求,普通類型參數(shù)
放在請(qǐng)求頭當(dāng)中
請(qǐng)求 url 如 :http://localhost:8001/eduservice/edu-teacher/test2?name=testName
這里的 name=testName 是傳遞的參數(shù)
后端
@PostMapping("/test2")
public R TestParam2(@ApiParam(name = "id", value = "查詢講師id", required = true) @RequestParam String name) {
System.out.println(name);
return R.ok();
}
前端api
export function testParam2(name) {
return request({
url: '/eduservice/edu-teacher/test2',
method: 'post',
params: { // 這里需要是 params 如果寫 data 會(huì)報(bào)錯(cuò)
name
}
})
}
調(diào)用請(qǐng)求
const b = 'testName'
eduTeacherAPI.testParam2(b).then(res => {
console.log(res)
})
三、接收參數(shù)注解 @RequestBody
post 請(qǐng)求,對(duì)象類型參數(shù)
前端傳遞對(duì)象,后端接收對(duì)象
放在請(qǐng)求體中的 payload / 負(fù)載
后端
@PostMapping()
@ApiOperation("條件分頁查詢講師")
public R pageWithConditions(@ApiParam(name = "queryTeacher", value = "查詢對(duì)象", required = false)
@RequestBody QueryTeacher queryTeacher) {}
前端api
export function list(page, limit, searchObj) {
return request({
url: `/eduservice/edu-teacher`, // 這里的 page / limit 就是拼接到 url 當(dāng)中的參數(shù)
method: 'post',
// data: { queryTeacher: searchObj } 注意這樣子寫是錯(cuò)誤的
data: searchObj
})
}
調(diào)用請(qǐng)求
文章來源:http://www.zghlxwxcb.cn/news/detail-426086.html
eduTeacherAPI
.list(this.pageObj.searchObj)
.then(res => {})
總結(jié)
例如:以上就是今天要講的內(nèi)容,本文僅僅簡單介紹了 前端傳遞普通類型參數(shù)和對(duì)象時(shí)前端傳遞的方式以及后端接受是注解的使用文章來源地址http://www.zghlxwxcb.cn/news/detail-426086.html
到了這里,關(guān)于前端傳遞對(duì)象參數(shù),以及后端接受參數(shù) @PathVariable @RequestParam @RequestBody 注解的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!