簡體   English   中英

如何通過expressjs的響應在前端捕獲錯誤?

[英]How catch error in the front-end from response of expressjs?

我的問題是下一個:

 //express server app.post('/register', (req, res) => { const { password, passwordConfirm } = req.body; if (password === passwordConfirm) { //... } else { res.status(400).json("Passwords aren't matching") } }) //react function onSubmitSignIn = () => { const { password, passwordConfirm } = this.state; let data = new FormData(); data.append('password', password); data.append('passwordConfirm', passwordConfirm); fetch('http://localhost:3001/register', { method: 'post', body: data }) .then(response => response.json()) .then(user => { //logs error message here console.log(user) }) //but I want to catch it here, and set the message to the state .catch(alert => this.setState({alert})) } 

當我發送狀態代碼,並將來自express的消息作為響應時,前端顯然將其識別為響應,這就是為什么它將消息以“用戶”身份記錄到控制台的原因。 但是如何發送到catch函數的錯誤呢?

如果由於某種原因無法fetch API,則fetch實際上只會出錯。 換句話說,它將因網絡錯誤而出錯。 2XX狀態代碼不會明確顯示錯誤。

您需要按照以下說明檢查ok屬性:

-

fetch('http://localhost:3001/register', {
    method: 'post',
    body: data
 })
 .then(response => {
     if (!response.ok) {
         throw new Error('my api returned an error')
     }
     return response.json()
 })
 .then(user => {

      console.log(user)
  })
  .catch(alert => this.setState({alert}))

問題是, fetch未將HTTP錯誤識別為Promise拒絕。

即使響應是HTTP 404或500,從fetch()返回的Promise也不會拒絕HTTP錯誤狀態。相反,它將正常解析,並且僅在網絡故障或任何阻止請求完成的情況下拒絕。

來源

您可以檢fetch存倉庫的鏈接源,該源還指出了處理HTTP錯誤狀態的建議。

如果拋出錯誤怎么辦:

app.get("/", function (req, res) {
  throw new Error("BROKEN"); // Express will catch this on its own.
});

然后在前端捕獲此錯誤?

請參閱此處以供參考

編輯

也許您應該使用return next()返回錯誤,以便在服務器方法中不處理其余代碼:

 app.get("/", function (req, res) {
     return next(new Error('BROKEN'));
 });
//express server
app.post('/register', (req, res) => {
 try {
  const {
   password,
   passwordConfirm
  } = req.body;
  if (password === passwordConfirm) {
   //...
  } else {
   res.status(400).json("Passwords aren't matching")
  }
 } catch (error) {
  res.status(500).send(error);
 }
})
//react function
onSubmitSignIn = () => {
 const {
  password,
  passwordConfirm
 } = this.state;
 let data = new FormData();
 data.append('password', password);
 data.append('passwordConfirm', passwordConfirm);

 fetch('http://localhost:3001/register', {
   method: 'post',
   body: data
  })
  .then(response => response.json())
  .then(user => {
   //logs error message here
   console.log(user)
  })
  //but I want to catch it here, and set the message to the state
  .catch(alert => this.setState({
   alert
  }))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM