Stories

Detail Return Return

fetch的使用記錄 - Stories Detail

如何用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參數?

  1. 設置Content-Typeapplication/json
  2. post參數轉換為字符串,需要用到JSON.stringify

如何解析響應?

需要對fetch返回的響應調用json方法。

因為fetch返回的是一個Response對象,不能直接讀取數據,所以需要對其先調用一下json方法,然後才能得到期望的數據對象。

user avatar yinzhixiaxue Avatar jcguanqi Avatar Z-HarOld Avatar kongsq Avatar rk405264704 Avatar jungang Avatar reddish Avatar iymxpc3k Avatar mi2nagemao Avatar fisher_feng Avatar evans_bo Avatar axuicn Avatar
Favorites 34 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.