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



我正在制作一个梦幻股票应用程序。当向API发出有效请求时,数据会按预期返回。如果股票不存在,则服务器返回"0";请求失败,状态代码为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.');
}
}

您只需要返回错误即可。目前你只是在安慰。记录错误,然后什么都不记录,这就是为什么它只是挂起的原因。

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);
})
})

最新更新