I’ve been learning React (kind of new to it) and I’m working on a project and I did an npm create vite@latest. So far everything works fine when I do run dev. However when I do run build, then go to the dist folder and open the index.html file I get a blank page.
So I do an inspect page in FireFox and I get these errors –
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resources at file:///assets/index-J7cny882.js. (Reason: CORS request not http)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resources at file:///assets/index-BAXwXR6k.css. (Reason: CORS request not http)
I’m bit puzzled by this. Don’t know whats wrong or how to fix it. I did come across some things online that mentioned adding "homepage": "." to package.json. I did that but didn’t help.
I appreciate the help.
Thanks.
2
Answers
The simplest solution is to use a local HTTP server to serve your built files. You can install one globally and use it:
Install a simple HTTP server:
Serve your dist folder:
This will host your project on http://localhost:3000 (or another port it provides), and you can access your project without encountering CORS issues.
When building with Vite, ensure the paths to your assets are relative or configured correctly. By default, Vite uses / as the base, which can cause issues if your project isn’t served from a root path.
Modify the vite.config.js file to set a relative base:
javascript
Then rebuild your project:
Now, the paths in the generated index.html file will be relative, and you can open it directly in the browser without needing a local server.
Browsers enforce stricter security policies for files opened with file:///. Using a local HTTP server (as shown in step 1) avoids these restrictions.
You need to serve the page actually. If you are using the Vite create for React you can do the following to test your build.
The preview command is already present on the package.json so you do not need to configure anything.
Keep in mind you should not use this for a production deploy. It only serves as a preview utility.
You can read the documentation here https://vite.dev/guide/cli#vite-preview