如何从expressjs的响应中捕获前端的错误?

Ger*_*áth 2 javascript express reactjs

我的问题是下一个:

//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}))
    }
Run Code Online (Sandbox Code Playgroud)

当我发送状态代码和来自 express 的消息作为响应时,前端显然将其识别为响应,这就是为什么它将消息作为“用户”记录到控制台的原因。但是如何将错误发送到 catch 函数呢?

Fra*_*teo 6

fetch如果由于某种原因无法推理 API,它实际上只会出错。换句话说,它会在网络错误时出错。对于非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}))
Run Code Online (Sandbox Code Playgroud)