Tuesday 25 August 2020

Data undefined when using Fetch API

I am building a YouTube Video downloader with Node and I am encountering an issue that I cannot seem to figure out. I am sending a response message or error depending on the outcome of the download. I am getting the error TypeError: Cannot read property 'error' of undefined whenever I get a response from my endpoint. Here is the client side code:fetch("/download", { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ url, }), }) .then((res) => { res.json(); }) .then((data) => { console.log(data); if (data.error) { console.log(data.error); } else { console.log("success"); } }) .catch((error) => { console.log(error); }); And here is a snippet from server side code:router.post("/download", (req, res) => { res.json({ message: "video downloaded" }); const { url } = req.body; const outputName = "video.mp4"; const outputPath = path.resolve(__dirname, outputName); const video = ytdl(url); console.log(video); video.pipe(fs.createWriteStream(outputPath)); video.once("response", () => { starttime = Date.now(); }); } When I log data in client side code it comes back as undefined when it should contain the message "video downloaded" and pass the error logic. The code works but I need to figure this out for error handling.

Submitted August 26, 2020 at 05:25AM by TheSlothJesus

No comments:

Post a Comment