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?

How Do I Fix 'XMLHttpRequest cannot load… Origin … is not allowed by Access-Control-Allow-Origin' Errors in Cross-Origin AJAX Requests?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 08:52:15418browse

How Do I Fix

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn