I'm building a custom headless CMS using WordPress as a backend and a React-based frontend. For authentication, I’m using the JWT Authentication for WP REST API plugin to allow users to log in and get a token.
However, when calling the JWT login endpoint (/wp-json/jwt-auth/v1/token) from my React frontend using fetch(), I encountered:
403 Forbidden errors
CORS errors (especially during login/signup)
After investigating, I learned that this issue is caused by CORS preflight requests (i.e., OPTIONS requests) being blocked or not handled correctly by WordPress or the JWT plugin.
🔍 Why this happens (CORS Preflight Explained)
When a browser sends a POST request with certain headers (e.g., Authorization), it first sends an OPTIONS request (called a preflight request) to ask the server if it’s allowed.
If the server does not respond properly to this preflight request, the browser cancels the actual request, resulting in a CORS error — even if your endpoint is valid.
This is common when:
Using JWT auth (needs Authorization header)
Using React, Axios, or Fetch with credentials, headers, or cross-origin settings
✅ Solution: Step-by-Step Fix
✅ Step 1: Handle OPTIONS (Preflight) Requests in WordPress
You need to explicitly handle OPTIONS requests for JWT routes:
php
Copy
Edit
add_action('rest_api_init', function () {
register_rest_route('jwt-auth/v1', '/token', [
'methods' => 'OPTIONS',
'callback' => function () {
return new WP_REST_Response(null, 204);
},
'permission_callback' => '__return_true',
]);
register_rest_route('jwt-auth/v1', '/token/validate', [
'methods' => 'OPTIONS',
'callback' => function () {
return new WP_REST_Response(null, 204);
},
'permission_callback' => '__return_true',
]);
});
🧠 Explanation:
This code tells WordPress to respond with HTTP 204 (No Content) when the browser sends a preflight OPTIONS request to the JWT login/validation endpoints. Without this, your React app’s requests will be blocked before they even reach the real login logic.
✅ Step 2: Add CORS Headers in WordPress
Now, allow your frontend to communicate with WordPress by setting CORS headers:
php
Copy
Edit
add_action('init', function () {
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
});
Erläuterung:
Dies stellt sicher, dass WordPress Anforderungen von Ihrem React Frontend (http: // localhost: 3000) ermöglicht. Es ermöglicht auch Anmeldeinformationen (z. B. Cookies oder Token) und kritische Header wie Autorisierung. von Unterstützung:
Apache
Kopieren
Bearbeiten < /p>
Header Setzen Sie immer Zugriffskontroll-Owl-Owl-Origin-Http: // Localhost: 3000 "
Header immer Setzen Sie Access-Control-Methods, Post, Options, Sagen Sie" Achs-"-Booker"
-Books ". Content-Typ "
Header Setzen
🧠 Explanation:
This adds CORS headers at the server level — especially helpful when using static or cached routes that WordPress might not dynamically control.
✅ Step 4: Test from React
Now try logging in from your React app using fetch():
js
Copy
Edit
fetch('http://task-6.local/wp-json/jwt-auth/v1/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'admin',
password: 'password'
})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
🧠 Explanation:
This POST request should now succeed because:
The server accepts OPTIONS preflight requests
CORS headers are correctly included in the response`enter code here`
No 403 or browser-blocking errors occur
Formatted by https://st.elmah.io
[code]I'm building a custom headless CMS using WordPress as a backend and a React-based frontend. For authentication, I’m using the JWT Authentication for WP REST API plugin to allow users to log in and get a token. However, when calling the JWT login endpoint (/wp-json/jwt-auth/v1/token) from my React frontend using fetch(), I encountered: 403 Forbidden errors CORS errors (especially during login/signup) After investigating, I learned that this issue is caused by CORS preflight requests (i.e., OPTIONS requests) being blocked or not handled correctly by WordPress or the JWT plugin. 🔍 Why this happens (CORS Preflight Explained) When a browser sends a POST request with certain headers (e.g., Authorization), it first sends an OPTIONS request (called a preflight request) to ask the server if it’s allowed. If the server does not respond properly to this preflight request, the browser cancels the actual request, resulting in a CORS error — even if your endpoint is valid. This is common when: Using JWT auth (needs Authorization header) Using React, Axios, or Fetch with credentials, headers, or cross-origin settings ✅ Solution: Step-by-Step Fix ✅ Step 1: Handle OPTIONS (Preflight) Requests in WordPress You need to explicitly handle OPTIONS requests for JWT routes: php Copy Edit
add_action('rest_api_init', function () { register_rest_route('jwt-auth/v1', '/token', [ 'methods' => 'OPTIONS', 'callback' => function () { return new WP_REST_Response(null, 204); }, 'permission_callback' => '__return_true', ]); register_rest_route('jwt-auth/v1', '/token/validate', [ 'methods' => 'OPTIONS', 'callback' => function () { return new WP_REST_Response(null, 204); }, 'permission_callback' => '__return_true', ]); });
🧠 Explanation: This code tells WordPress to respond with HTTP 204 (No Content) when the browser sends a preflight OPTIONS request to the JWT login/validation endpoints. Without this, your React app’s requests will be blocked before they even reach the real login logic. ✅ Step 2: Add CORS Headers in WordPress Now, allow your frontend to communicate with WordPress by setting CORS headers: php Copy Edit
add_action('init', function () { header("Access-Control-Allow-Origin: http://localhost:3000"); header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE"); header("Access-Control-Allow-Headers: Authorization, Content-Type"); }); [/code] 🧠 Erläuterung: Dies stellt sicher, dass WordPress Anforderungen von Ihrem React Frontend (http: // localhost: 3000) ermöglicht. Es ermöglicht auch Anmeldeinformationen (z. B. Cookies oder Token) und kritische Header wie Autorisierung. von Unterstützung: Apache Kopieren Bearbeiten < /p>
Header Setzen Sie immer Zugriffskontroll-Owl-Owl-Origin-Http: // Localhost: 3000 " Header immer Setzen Sie Access-Control-Methods, Post, Options, Sagen Sie" Achs-"-Booker" -Books ". Content-Typ " Header Setzen[code]🧠 Explanation: This adds CORS headers at the server level — especially helpful when using static or cached routes that WordPress might not dynamically control. ✅ Step 4: Test from React Now try logging in from your React app using fetch(): js Copy Edit
.then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); 🧠 Explanation: This POST request should now succeed because: The server accepts OPTIONS preflight requests CORS headers are correctly included in the response`enter code here` No 403 or browser-blocking errors occur
Dies ist der Fehler, den ich derzeit gegenübersteht. /> Ressource. Wenn eine undurchsichtige Antwort Ihren Anforderungen dient, setzen Sie den
-Modus der Anforderung auf 'No-Cors', um die Ressource...
Ich entwickle gerade eine Website und habe Probleme beim Anzeigen meiner Schriftsymbole in Firefox. Jeder Browser außer Firefox kann meine Schriftsymbole laden und anzeigen, aber bei Firefox erhalte...
Ich entwickle gerade eine Website und habe Probleme beim Anzeigen meiner Schriftsymbole in Firefox. Jeder Browser außer Firefox kann meine Schriftsymbole laden und anzeigen, aber bei Firefox erhalte...
Das Programm funktioniert technisch, aber ich erhalte immer wieder den Fehler:
kann javax.swing.jbutton.addactionListener (java.awt.event.ActionListener) nicht aufrufen. Richtig.
Hier ist der...
Problem:
Ich baue ein Flask-Backend mit Flask-restful, Flask-jwt-erweitert und postgresql. Beim Testen von JWT -Token -Ablauf über Postmanen führen abgelaufene Token konsistent zu einem 500 internen...