Home >Web Front-end >JS Tutorial >How Do I Fix 'XMLHttpRequest cannot load… Origin … is not allowed by Access-Control-Allow-Origin' Errors in Cross-Origin AJAX Requests?
Cross-Origin Resource Sharing (CORS) and Error Handling
When attempting Ajax requests to remote PHP servers, it's common to encounter the error, "XMLHttpRequest cannot load… Origin … is not allowed by Access-Control-Allow-Origin." This occurs due to CORS limitations in web applications.
Resolving the Issue
The preferred solution is to adjust the response header on the responding server by adding:
Access-Control-Allow-Origin: *
This grants permission for cross-domain Ajax requests. In PHP, modify the response as follows:
<?php header('Access-Control-Allow-Origin: *'); ?>
Alternatively, you can set this header in Apache configuration or htaccess file.
Caution: Wildcard Considerations
Using a wildcard allows all domains to access your resources, potentially exposing users to attacks. Only use a wildcard if necessary. To specify specific domains, whitelist them:
<?php header('Access-Control-Allow-Origin: http://example.com') ?>
Please exercise caution when implementing CORS to protect user security and data integrity.
The above is the detailed content of How Do I Fix 'XMLHttpRequest cannot load… Origin … is not allowed by Access-Control-Allow-Origin' Errors in Cross-Origin AJAX Requests?. For more information, please follow other related articles on the PHP Chinese website!