When attempting to retrieve data from a REST API while working on a localhost, you may encounter the error message "Fetch API cannot load . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." This error stems from the "Same Origin Policy" that browsers enforce, restricting resources from different origins (domains, ports, and protocols) from interacting with each other.
If you lack control over the server hosting your REST API and the only issue with its responses is the absence of the required Access-Control-Allow-Origin header, you can leverage a CORS proxy to facilitate the request.
Here are steps to set up your own proxy:
Once deployed, prefix your REST API URL with the generated proxy URL. For instance: https://cryptic-headland-94862.herokuapp.com/https://example.com.
The request in the question triggers a preflight request due to the inclusion of the Authorization header. To prevent this preflight, consider using one of the following techniques:
For requests that involve credentials, browsers restrict frontend JavaScript code access to the response if the Access-Control-Allow-Origin header's value is '*'. In such cases, the value must precisely match the origin of your frontend code (e.g., http://127.0.0.1:3000).
Note: Avoid using Chrome CORS plugins, as they simply inject a generic Access-Control-Allow-Origin: * header into responses, which may lead to unexpected behavior. Utilize curl commands with the -H flag for reliable testing.
The above is the detailed content of How to Solve the 'No 'Access-Control-Allow-Origin' header' Error When Fetching Data from a REST API?. For more information, please follow other related articles on the PHP Chinese website!