Hey hey - I got it! there was no data being sent through was because I was trying to use a "no-cors" in the request header! As soon as I sorted that out and worked out how to read the stream object it works just fine. Thank you Gabriel for your patience with this utter noob 😉
For anyone who's interested - this is my front end script;
async function fetchAndReadStream() {
try {
// Send a GET request to the server
const response = await fetch("http://127.0.0.1:8000", {
method: 'GET',
mode: "cors",
headers: {
'Content-type': 'text/html',
'Accept': 'text/html'
}
});
console.log(response)
let result = ''
// Check if the response body is a readable stream
if (response.body) {
// Create a reader from the response body
const reader = response.body.getReader();
let decoder = new TextDecoder(); // To decode stream chunks into text
while (true) {
// Read the next chunk
const {
done,
value
} = await reader.read();
if (done) {
break; // Stream has finished
}
result += decoder.decode(value, {
stream: true
}); // Decode and append chunk
}
console.log('Received stream content:', result);
// Optionally render the content in the browser
} else {
console.log('No readable stream found in the response body.');
}
} catch (error) {
console.error('Error fetching or reading the stream:', error);
}
}
// Call the function to fetch and read the stream
fetchAndReadStream();
and this is my python server script;
from http.server import HTTPServer, BaseHTTPRequestHandler
import subprocess
import sys
class CORSRequestHandler(BaseHTTPRequestHandler):
def _set_headers(self):
print("Setting response headers")
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.end_headers()
def do_GET(self):
print("Handle GET request")
self._set_headers()
subprocess.run("curl -o c:\test\test.csv \"https://myimaginarywebsite.com/getdata\"")
in_file = open("c:\test\test.csv", "rb")
data = in_file.read()
in_file.close()
print("writing data")
self.wfile.write(bytes("<html><head><title>Returned Data</title></head>", "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes(data))
self.wfile.write(bytes("</body></html>", "utf-8"))
self.close_connection
def do_OPTIONS(self):
print("Handle preflight OPTIONS requests for CORS")
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.end_headers()
if __name__ == "__main__":
host = "localhost"
port = 8000
server = HTTPServer((host, port), CORSRequestHandler)
print(f"Server running at {host}:{port}")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nShutting down server...")
server.server_close()