Home >Web Front-end >JS Tutorial >How Can I Fix 'Origin is not allowed by Access-Control-Allow-Origin' CORS Errors?

How Can I Fix 'Origin is not allowed by Access-Control-Allow-Origin' CORS Errors?

Linda Hamilton
Linda HamiltonOriginal
2024-12-30 10:35:08861browse

How Can I Fix

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!

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