如何用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方法,然後才能得到期望的數據對象。