enable CORS for local http server
Asked Answered
M

3

12

I hosted my local files with http server. Just install on my Mac HTTP server with command:

npm install --global http-server

Then I start this server in needed directory with the command:

http-server

I had the CORS policy problem when trying to fetch my local HTML file from HTTP server response. It was blocked. Blocked by CORS policy

Malvoisie answered 7/8, 2020 at 8:10 Comment(1)
you can also use npx http-server ... paramsMunmro
M
25

All I need to do for resolving this issue just to start HTTP server with cors option:

http-server --cors
Malvoisie answered 7/8, 2020 at 8:10 Comment(3)
Is there a particular order the arguments have to be in? I have --cors and it is not working for me.Protecting
Make sure you're not trying to pass that argument to your task (e.g. in your Terminal). In my case I added it to my package.json "start-server" script ( "start-server": "http-server --cors -c-1 -p 8081") @ProtectingSpheroidal
it didn't work for me, the problem was that the CORS headers (probably the options request call) is cached. When I disabled cache, it finally worked.Cretonne
H
1

Was unable to get http-server running with CORS support (different browsers, disabling cache... nothing helped).

As the related bug ticket is still an ongoing discussion, here is an alternative that worked for me out of the box using local-web-server:

  1. npm i local-web-server --global
  2. ws --cors.origin http://<your domain> --cors.credentials

You might add --https -p 443 if you need to simulate local SSL support.

Heal answered 11/1, 2021 at 8:34 Comment(1)
http-server worked for me with --cors flag. Make sure you use the latest version.Corinthian
P
1

One of the possible solutions is simply serve package via npx

eg. npx serve ./folder -l 3003 --cors

The port can be dropped or specified

Promising answered 16/8, 2023 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.