1、发送get请求
使用fetch发送get(默认get)形式请求,返回数据采用json格式,需要两次.then才能获取到数据,如下res就是获取到的数据
fetch(url).then(res => res.json()).then(res => console.log(res))
2、发送json数据
配置请求头 ‘Content-Type’: ‘application/json’
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // 发送的json数据
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json()).then(res => console.log(res))
3、发送表单数据
配置请求头 ‘Content-Type’: ‘application/x-www-form-urlencoded’
fetch(url, {
method: 'POST', // or 'PUT'
body: "username=zhangsan&age=11", // 发送的json数据
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
}).then(res => res.json()).then(res => console.log(res))