I have hosted a site for a static API coming from a JSON file. The fake API link is api.example.com/db.json
.
While I am checking the URL with postman I am getting 200 status code. But while I am fetching it from Javascript it's showing this error Access to fetch at 'http://api.example.com/db.json' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am running the web server using nginx and it's a simple site package which have only one HTML page and that db.json file. Where I should add the Access-Control-Allow-Origin: https://www.example.com
?
Also, I Tried json-server
I even tried json-server
. It's running locally but while I am hosting it in nginx server and tried to run pm2 start --name=static_api npm run json:server
pm2 showing this error
[PM2] Starting /usr/local/bin/npm in fork_mode (1 instance)
[PM2] Done.
[PM2][ERROR] Script not found: /var/www/html/static_api/run
Is there any way I can run the fake API aka json-server
with Nginx?
Thanks.
CodePudding user response:
Add add_header Access-Control-Allow-Origin "https://www.example.com"; to your nginx server block (and other CORS headers the same way, if needed).
Answer by Ivan Shatsky