I’m encountering a “NetworkError when attempting to fetch resource.” error in a fetch call on the client-side and then a following page refresh, even though my server-side code successfully fetches and downloads the image. I’m not sure why the client is throwing this error when the server indicates success.
Front-end API call:
//config.servername = "" my package.json is proxying to my back end on localhost
export const uploadCoverImage = async (isbn, imageUrl) => {
try {
const response = await fetch(`${config.servername}/api/downloadCover/${isbn}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ imageUrl }),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error uploading cover image', error);
throw error;
}
};
Server-side endpoint:
app.post('/api/downloadCover/:isbn', async (req, res) => {
const { isbn } = req.params;
const { imageUrl } = req.body;
if (!imageUrl) {
return res.status(400).json({ message: "Image URL is required" });
}
const destination = path.join(__dirname, '../client/public/covers', `${isbn}.jpg`);
const file = fs.createWriteStream(destination);
https.get(imageUrl, (response) => {
if (response.statusCode !== 200) {
res.status(500).json({ message: 'Failed to fetch image', error: `Server responded with status code ${response.statusCode}` });
return;
}
response.pipe(file);
file.on('finish', () => {
file.close();
res.json({ message: 'Image downloaded successfully' });
});
}).on('error', (err) => {
console.error('Error fetching the image:', err.message);
fs.unlink(destination, () => res.status(500).json({ message: 'Error fetching the image', error: err.message }));
});
file.on('error', (err) => {
console.error('Error writing the file:', err.message);
fs.unlink(destination, () => res.status(500).json({ message: 'Error writing the image', error: err.message }));
});
});
Despite these efforts, the client still throws a “NetworkError when attempting to fetch resource.” error. What could be causing this issue, and how can I resolve it?
What I’ve tried:
- Checked the server logs, and the image is downloaded successfully.
- Ensured the server responds correctly after the image is downloaded.
- Verified that there are no network issues between the client and server, the server and client are on localhost.
- Enables cors and allowed localhost.
- Enabled proxy in json.packages for he server
- Logged res on the server and compared to another endpoint looking for anomalies.
- Inspected network tab, no response is present.
- Inspected traceback, the error is thrown by the fetch itself in
overrideMethod