如何用fetch发动post申请
上面是一个用fetch
发动的post
申请示例:
fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'tomcat',
}),
})
.then(res => res.json())
.then(res => {
console.log('res', res);
});
注意事项:
如何传递post
参数?
- 设置
Content-Type
为application/json
- 将
post
参数转换为字符串,须要用到JSON.stringify
如何解析响应?
须要对fetch
返回的响应调用json
办法。
因为fetch
返回的是一个Response
对象,不能间接读取数据,所以须要对其先调用一下json
办法,而后能力失去冀望的数据对象。
发表回复