Solving CORS Preflight Request Access Control Check Failures: A Guide for Local Development Environments

Dec 07, 2025 · Programming · 9 views · 7.8

Keywords: CORS | Preflight Request | Cross-Origin Resource Sharing | Local Development | Server Configuration

Abstract: This article provides an in-depth exploration of the Cross-Origin Resource Sharing (CORS) mechanism, focusing specifically on the root causes of preflight request failures. Through analysis of a case where a frontend JavaScript script attempts to check the status code of an external website and encounters CORS errors, the article explains the security mechanisms of CORS, the role of preflight requests, and why setting CORS headers on the client side is ineffective. The article emphasizes server-side CORS header configuration solutions for local development environments, including methods using Nginx and .htaccess files, supplemented with cross-platform solutions for Node.js and Flutter. Written in a rigorous technical paper style, it includes core concept analysis, error diagnosis, solution implementation, and code examples to help developers fundamentally understand and resolve CORS issues.

Core Principles of CORS Mechanism and Preflight Requests

Cross-Origin Resource Sharing (CORS) is a security mechanism implemented by modern browsers to prevent malicious websites from accessing resources from other domains via scripts. When a web application attempts to request resources from a different origin (protocol, domain, or port), the browser automatically performs CORS checks. Preflight requests are a critical component of the CORS mechanism; for HTTP methods that may have side effects on server data (such as PUT, DELETE, etc.) or requests using custom HTTP headers, the browser first sends an OPTIONS method preflight request to verify whether the server permits the actual request.

Error Case Analysis and Root Causes

In the provided case, the developer attempts to check the status code of an external website (e.g., https://example.com) using XMLHttpRequest from frontend JavaScript. The code incorrectly sets CORS-related headers on the client side:

http.setRequestHeader("Access-Control-Allow-Origin", "http, https");
http.setRequestHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTONS");
http.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

The fundamental error here is that CORS headers must be set by the requested server (the resource provider), not by the requester. Before sending the actual GET request, the browser first sends a preflight request (OPTIONS method) to the target server. If the server response does not include the correct Access-Control-Allow-Origin header, the browser blocks the actual request and throws the error: "Response to preflight request doesn't pass access control check." The 'origin: null' in the error message indicates the request originated from the local file system (file:// protocol), which further intensifies CORS restrictions.

Server-Side CORS Configuration Solutions

To resolve this issue, CORS policies must be configured on the server providing the resources. Below are configuration methods for different server environments:

Nginx Server Configuration

In the Nginx configuration file, CORS headers can be added for specific locations or the entire server. The following configuration allows cross-origin requests from a specified origin:

add_header Access-Control-Allow-Origin example.com;

To allow all origins, a wildcard can be used, but security risks should be considered:

add_header Access-Control-Allow-Origin "*";

Apache Server Configuration via .htaccess

For shared hosting or situations where server configuration cannot be directly modified, the following directives can be added to the .htaccess file in the project root directory:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"

Ensure file permissions are set to 644 for proper server reading. This method is particularly suitable for static website hosting environments.

Node.js Server Configuration

When using the Express framework, the cors middleware simplifies configuration:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors({ origin: true })); // Enable CORS, allowing all origins
app.use(express.json());

// Route handling
app.post('/', async (req, res) => {
    // Request handling logic
});

For more granular control, specific options can be configured:

app.use(cors({
    origin: 'http://localhost:3000', // Allow only specific origin
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));

Client-Side Alternatives and Considerations

If controlling the target server's CORS configuration is not possible, consider the following alternatives:

  1. Proxy Server: Set up a proxy on a local or owned server to convert cross-origin requests into same-origin requests.
  2. JSONP (GET requests only): For simple requests, JSONP can bypass CORS restrictions, though this method is gradually being phased out in modern API design.
  3. Server-Side Checking: Move status checking logic to the backend server, with the frontend obtaining results via same-origin requests.

In cross-platform frameworks like Flutter, while Access-Control-Allow-Origin headers can be set on the client side, this only applies to certain environments (e.g., mobile apps) and still requires server-side configuration in web browsers. Flutter Web example:

final headers = <String, String>{
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
};
final response = await http.post(
    Uri.parse(url),
    headers: headers,
    body: jsonEncode(data),
);

It is important to note that browsers ignore client-side CORS headers, so the above Flutter code may still require server-side cooperation in web environments.

Security Considerations and Best Practices

When configuring CORS, follow the principle of least privilege:

By correctly understanding the CORS mechanism and implementing appropriate configurations on the server side, developers can securely enable cross-origin resource access while maintaining web application security.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.