0%

Fetch模拟请求

Fetch模拟请求

当有接口需要测试的时候,以前的想法都是采用postman保存URL,并从浏览器中复制cookie进行测试。最近发现了fetch这个工具,可以在浏览器控制台下模拟请求,直接就可以使用浏览器的用户环境,无需构造cookie,请求头等。这个工具对于简单的接口测试还是非常有效率的!

GET请求

json对象的数据格式

以json形式打印

1
2
3
4
5
fetch('apiUrl').then(res => {
return res.json()
}).then(data => {
console.log(data);
})

text文本的数据格式

以文本形式打印

1
2
3
4
5
6
fetch('apiUrl').then(res => {
return res.text()
}).then(data => {
console.log(data);
})

POST请求

form 格式

1
2
3
4
5
6
7
8
9
fetch("apiUrl", {
method: "post",
headers: {
'Content-Type': "application/x‐www‐form‐urlencoded"
},
body: "name=CourageHe&age=23"
}).then(res => res.json()).then(res => {
console.log(res);
})

application/json编码格式:

1
2
3
4
5
6
7
8
9
10
11
fetch("apiUrl", {
method: "post",
headers: {
'Content-Type': "application/json"
},
body: JSON.stringify({
"name":1
})
}).then(res => res.json()).then(res => {
console.log(res);
})
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道