如何正確取得 fetch 的狀態?
P粉124070451
P粉124070451 2023-09-08 18:25:24
0
1
513

我在我的 api 中執行提取,它返回 201 狀態,但是當我嘗試在變數中接收它時,狀態變得很奇怪。

useEffect(() => {
async function Verify (test) {
 await fetch("/api/test", {
  method: "POST", 
  headers: {
   'Content-Type': 'application/json',
  },
  body: JSON.stringify({test: test}),
 }).then((response) => {
  res = response.status; 
  console.log(res); //thats print '201'
  return res;
 });
}
const status = Verify(test);
console.log(status); //thats print 'Promise { <state>: "fulfilled", <value>: 201 }'

}

P粉124070451
P粉124070451

全部回覆(1)
P粉509383150

如果您希望status等於Verify的結果,您需要await它。

const status = await Verify(test);

此外,我建議重構您的程式碼以在各處使用 await 來簡化流程。嘗試這樣的事情:

async function Verify (test) {
  const res = await fetch('/api/test', {
    method: 'POST', 
    headers: {
     'Content-Type': 'application/json',
    },
    body: JSON.stringify( { test } ),
  });
  
  if (!res.ok) {
    throw new Error('Not-ok response from server');
  }

  return res;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!