Im making a fantasy stock app. when making a valid request to the API, the data gets returned as expected. If a stock does not exist, the server returns "Request failed with status code 404". I am trying to handle the error by logging the status to the console but the app does not catch the 404 error and the request stays pending. I cant find a way to handle the error so that it exits the promise to show the user that the stock is invalid.
my backend is as follows
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)
})
})
my front end
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.');
}
}
You just need to return the error. Currently you're just console.logging the error and then nothing else, thats why it just stays pending.
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);
})
})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments