When trying to load a Python script from a separate file using PyScript, I get the following error:
JsException(TypeError: Failed to fetch)
How can I fix this error and run the Python script?
My source code consists of two files, hello.html and hello.py.
hello.html:
<html>
<head>
<title>Hello PyScript</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<py-env>
- paths:
- /hello.py
</py-env>
<body>
<py-script src="./hello.py"></py-script>
</body>
</html>
hello.py:
print("Hello, PyScript!")
In the developer tools, the console displays the following error:
Access to fetch at 'file:///hello.py' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
I am opening the file by double-clicking on it in file explorer.
This error occurs because you are trying to load the file locally, using the
file
protocol scheme. (In other words, the URL of the page looks something likefile:///path/to/hello.html
.) When using thefile
protocol scheme, all major browsers disallow loading other files in the same folder for security reasons. Instead, you need to set up a local server to host your files.For example, you can set up a test server with Python by running the following command in the folder your files are in:
(This assumes you have Python 3 installed, and the
python
command points to your Python 3 installation.)Once you have started your local server with this command, you will be able to access hello.html at the URL http://localhost:8000/hello.html. When you access it this way, your browser will see that hello.html and hello.py both come from the same origin, so it will allow you to load hello.py from hello.html.