I'm developing a web application using Rust's Axum framework and have encountered a network error when trying to implement a video download feature. The issue arises when my server-side function, which handles video downloads, is called. Removing this function resolves the error, suggesting the issue is related to how the function operates.
Environment:
- Rust with Axum framework
- JavaScript (client-side)
Problem:
When I trigger a video download from the client side (using JavaScript fetch
to send a POST request), the server (Axum in Rust) throws a "network error fetching resource." This error does not occur when I remove the video download handling function on the server.
Server-side code snippet:
use axum::{
response::{Response, IntoResponse},
http::{StatusCode, header::HeaderMap},
Json,
};
use reqwest::header;
use serde::Deserialize;
use crate::utils::youtube::download_youtube;
#[derive(Deserialize)]
pub struct VideoRequest {
site: String,
url: String,
}
pub async fn download_video(Json(payload): Json<VideoRequest>) -> impl IntoResponse {
let response_body = match payload.site.as_str() {
"youtube" => {
format!("Processing youtube with URL: {}", payload.url)
},
"type2" => format!("Processing type2 with URL: {}", payload.url),
_ => format!("Unknown type: {}", payload.site),
};
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "text/plain")
.body(response_body)
.unwrap()
}
Client-side code snippet:
document.addEventListener('DOMContentLoaded', () => {
const downloadButton = document.getElementById('downloadButton');
if (downloadButton) {
downloadButton.addEventListener('click', function(e) {
e.preventDefault(); // Prevent the default button click action
const videoUrl = document.getElementById('videoUrl').value;
fetch('http://127.0.0.1:3000/api/v1/download', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ site: "youtube", url: videoUrl })
})
.then(response => console.log(response.status))
.catch(error => {
console.error('Error:', error);
});
})
}
});
Attempts to resolve:
- Checked CORS settings on the server (seem to be configured correctly).
- The server works fine for other routes and functionalities.
Questions:
- What could be causing the network error specifically when the video download function is active?
- Are there any best practices for handling long-running tasks like video downloads in Axum to avoid blocking or timeouts?
- Could this be related to async handling in Rust, and if so, how can I better structure my async function to prevent such issues?
Any insights or suggestions on how to troubleshoot or resolve this would be greatly appreciated!