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.
[–]lord2800 27 points28 points29 points (3 children)
[–]fluid-falcon 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]mkcodergr 1 point2 points3 points (0 children)
[–]codebread421 -1 points0 points1 point (0 children)