我的问题是下一个:

//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,则实际上只会出错。换句话说,它将因网络错误而出错。非2XX状态代码不会显式错误。

您需要按照此处所述检查ok属性:

  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
  • https://developer.mozilla.org/en-US/docs/Web/API/Response/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}))
    

    关于javascript - 如何通过expressjs的响应在前端捕获错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53022281/

    10-12 12:42
    查看更多