fetch的使用记录
文章目录
如何用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方法,然后才能得到期望的数据对象。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论