ARTICLE AD BOX
Body of the Question I am developing a web tool (a Single Page Application built with vanilla HTML, CSS, and JS) to manage publications on multiple client WordPress sites. I utilize the native WordPress Application Passwords feature for authentication by sending the Authorization: Basic ... header.
The Problem: For some sites, the connection works perfectly. However, for others, I encounter CORS (Cross-Origin Resource Sharing) errors that block the request immediately.
Upon inspecting the browser's Network tab, I notice that the "Preflight" (OPTIONS) request returns a 403 Forbidden or 404 status, causing the browser to block the subsequent GET or POST request.
Scenario:
Front-end: JavaScript (fetch API) running in the browser (client-side).
Back-end: Varied WordPress installations (different hosting providers).
Authentication: Authorization header with base64 (User + Application Password).
Simplified Code: Here is the snippet of the function where the error occurs (attempting to list categories):
JavaScript
async function loadWpCategories() { const baseUrl = "https://site-exemplo.com"; const endpoint = "/wp-json/wp/v2/categories?per_page=100"; // Credenciais geradas no WP (Application Passwords) const user = "admin"; const appPassword = "xxxx xxxx xxxx xxxx"; // Header Basic Auth const authHeader = "Basic " + btoa(user + ":" + appPassword); try { // O erro dispara aqui let resp = await fetch(baseUrl + endpoint, { method: 'GET', headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' } }); if (!resp.ok) throw new Error("Status " + resp.status); const data = await resp.json(); console.log(data); } catch (err) { console.error("Erro ao carregar categorias:", err); } }The Console Error:
Access to fetch at '...' from origin '...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Attempts:
I noticed the error happens specifically when I add the Authorization header. Without it (for public routes), CORS often doesn't block it, but I need it for authentication.
I tried adding mode: 'cors' to the fetch options, but the error persists.
Question: Is there any way to resolve this via code on my Front-end (JavaScript)? Or does this behavior confirm that the client WordPress servers are blocking OPTIONS requests or external authorization headers, and the only solution is to install a CORS plugin on the destination WordPress?
