Home >Web Front-end >JS Tutorial >How Can I Fix 'Origin is not allowed by Access-Control-Allow-Origin' CORS Errors?
Access Denied Due to CORS
When attempting to perform an Ajax request to a remote server, you may encounter the error "Origin is not allowed by Access-Control-Allow-Origin." This error occurs when the request is made from a different domain than the server that is hosting the resource, which is a security measure known as Cross-Origin Resource Sharing (CORS).
To resolve this issue, you can add the following response header to the server's response:
Access-Control-Allow-Origin: *
This header allows cross-domain Ajax requests, but it should be used with caution as it effectively disables CORS protection. If possible, you should whitelist specific domains instead of using a wildcard.
PHP Implementation
In PHP, you can modify the response header by adding the following line:
header('Access-Control-Allow-Origin: *');
Alternatively, you can set the header in the Apache configuration or htaccess file.
Whitelist Specific Domains
If you only need to allow requests from specific domains, you can use the following header syntax:
header('Access-Control-Allow-Origin: http://example.com');
The above is the detailed content of How Can I Fix 'Origin is not allowed by Access-Control-Allow-Origin' CORS Errors?. For more information, please follow other related articles on the PHP Chinese website!