Cross -Ursprungsfehler (Senden der Anforderung von React to WordPress Headless Endpoint, machte mein JWT -Plugin)Php

PHP-Programmierer chatten hier
Anonymous
 Cross -Ursprungsfehler (Senden der Anforderung von React to WordPress Headless Endpoint, machte mein JWT -Plugin)

Post by Anonymous »

Code: Select all

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

Code: Select all

🧠 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

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post