繁体   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