未找到返回状态代码 404 的 API 请求

时间:2021-07-19 00:49:08

标签: node.js reactjs

我正在制作一个梦幻股票应用。向 API 发出有效请求时,数据将按预期返回。如果股票不存在,服务器返回“请求失败,状态码为 404”。我试图通过将状态记录到控制台来处理错误,但应用程序没有捕获 404 错误并且请求保持挂起。我找不到处理错误的方法,以便它退出向用户显示库存无效的承诺。

我的后台如下

app.get('/api/stocks', (req, res) => {
    const stockName = req.query.stockName
    axios({
        method: 'get',
        url: `https://sandbox.iexapis.com/stable/stock/${stockName}/quote?token=${testSecretKey}`
    })
        .then(response => {
            res.json(response.data);
        }).catch(err => {
        console.log(err.message)
    })
})

我的前端

    handleSubmit = async e => {
        e.preventDefault();
        if (this.state.searchTerm !== '') {
            await axios.get("api/stocks", {
                params: {
                    stockName: this.state.searchTerm
                }
            })
                .then((res, req) => {
                    if (res.status === 200) {
                        this.setState({ stock: res.data, searchTerm: '', isStockValid: true });
                        console.log(res.status);
                    } else {
                        console.log(res.status)
                    }
                })
                // .catch(() => { console.log('error 404') });
            
            } else {
                alert('Enter a stock symbol. Example: AAPL for Apple inc.');
        }
    }

1 个答案:

答案 0 :(得分:0)

您只需要返回错误。目前,您只是在控制台。记录错误,然后没有别的,这就是为什么它只是挂起。

app.get('/api/stocks', (req, res) => {
    const stockName = req.query.stockName
    axios({
        method: 'get',
        url: `https://sandbox.iexapis.com/stable/stock/${stockName}/quote?token=${testSecretKey}`
    })
        .then(response => {
            res.json(response.data);
        }).catch(err => {
            console.log(err.message);
            res.send(err);
    })
})