Home > Web Front-end > JS Tutorial > Why Does My Localhost CORS Request Fail to stackoverflow.com Despite Correct Server Headers?

Why Does My Localhost CORS Request Fail to stackoverflow.com Despite Correct Server Headers?

Mary-Kate Olsen
Release: 2024-12-16 11:31:11
Original
852 people have browsed it

Why Does My Localhost CORS Request Fail to stackoverflow.com Despite Correct Server Headers?

Localhost CORS Header Issue

Despite configuring the server with appropriate CORS headers, a user encounters difficulties using localhost as the origin in their client script.

Server Configuration

The server is set up with the following header:

Access-Control-Allow-Origin:http://localhost
Copy after login

Client Script

The client script uses the XMLHttpRequest object to make a request to 'http://stackoverflow.com/'.

var xhr = new XMLHttpRequest();
xhr.onload = function() {
   console.log('xhr loaded');
};
xhr.open('GET', 'http://stackoverflow.com/');
xhr.send();
Copy after login

Error

However, the request fails with the following error:

XMLHttpRequest cannot load http://stackoverflow.com/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
Copy after login

Solution

While the server configuration appears correct, the issue lies in the use of 'localhost' as the origin in the client script.

Chrome does not support localhost for CORS requests due to a bug that was marked as "WontFix" in 2014.

Workaround

To avoid this issue, use a domain that resolves to 127.0.0.1, such as 'localho.st', or launch Chrome with the '--disable-web-security' flag for testing purposes.

The above is the detailed content of Why Does My Localhost CORS Request Fail to stackoverflow.com Despite Correct Server Headers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template