场景描述
在使用MockJS进行模拟数据的时候,会遇到一种场景,当参数=1时,展示A类数据,当参数=B时,展示B类数据,为了实现这场景,那就要在模拟数据时拿到请求参数?
实现逻辑
mock方法的编写如下:
ts
export default [
{
url: '/xxxxx/get',
method: 'post',
timeout,
response: (e) => {
if(e.body && e.boby.type == 1){
return A结果
}
if(e.body && e.boby.type == 2){
return B结果
}
return null
}
}
] as MockMethod[]
在response
内e
参数,字段如下,可以看见boby内有请求头信息,如此,我们可以根据这个boby进行判断,来模拟不同的结果,这样就会使得模拟的数据连贯。
完整的response数据如下:
json
{
"url": "/xxxxx/get",
"body": {
"type": 1
},
"query": {},
"headers": {
"host": "localhost:4000",
"connection": "keep-alive",
"content-length": "68",
"pragma": "no-cache",
"cache-control": "no-cache",
"sec-ch-ua": "\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"",
"accept": "application/json, text/plain, */*",
"content-type": "application/json",
"sec-ch-ua-mobile": "?0",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"sec-ch-ua-platform": "\"Windows\"",
"origin": "http://localhost:4000",
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
"referer": "http://localhost:4000/",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh-CN,zh;q=0.9"
}
}
上面是post请求数据存储在body
内,如果是get请求,参数会在query
内进行展示。