0

I am learning how to code in react.js and I have run into a problem. When I run the react code inside the script tags within my HTML page it runs fine, but as soon as I try to link the script tags to a separate .js file it gives me an error:

Here is my HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>My Website</title>

        <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
        <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    </head>
    <body>
        <div id="react-container"></div>
        <script src="test.js" type="text/babel"></script>
    </body>
</html>

And my test.js file:

const component = <h1>Hello World</h1>

ReactDOM.render(<component />, document.getElementById("react-container"));

The React.js code may very well be wong; I don't think that's the issue. When I run the file there is just a blank page, no Hello World message. Here is the full error:

Access to XMLHttpRequest at 'file:///C:/Users/samue/OneDrive/Desktop/EvoGenesis%20Website/react-integrated/test.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

(I shortened it for the title).

There is another error as well: Failed to load resource: net::ERR_FAILED

For reference the first error is apparently on the 1st line of the HTML file and the second on the first line of the JS file.

  • 3
    Browsers consider all `file://` URLs to be resources that are mutually untrustworthy. It'd make your life easier (and be educational) to find a simple HTTP server instead of using `file://` URLs. – Pointy Mar 06 '23 at 15:07
  • Ok, so if I launched this as a website what would the link look like? Would it be http://mywebsite.com/test.js? – Samuel Crawford Mar 06 '23 at 15:08
  • https://reactjs.org/tutorial/tutorial.html – epascarello Mar 06 '23 at 15:24
  • 1
    You can run a simple server on your workstation, and it'll be `http://localhost:1234` (or some other port number) – Pointy Mar 06 '23 at 15:28
  • Thanks, I do have a website set up I can use but that will be faster. I'll create one. – Samuel Crawford Mar 06 '23 at 19:14

0 Answers0