CORS error wrong endpoint

User
Access to fetch at 'https://wprock.ddev.site/graphql' from origin 'https://wprock.ddev.site:5173' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
Home.jsx:9

but actual is
https://wprock.ddev.site/wp/graphql.

POST https://wprock.ddev.site/graphql net::ERR_FAILED

Assistant
Got it β€” let’s break it down **clearly**:

πŸ”΄ **The core of your error:**

– You are trying to `fetch` from
`https://wprock.ddev.site/graphql`
– But you **should** be hitting
`https://wprock.ddev.site/wp/graphql` (βœ… correct path).

Because `/graphql` **does not exist**, the server sends an **empty / bad / no CORS** response, causing:

CORS policy: No 'Access-Control-Allow-Origin' header...
net::ERR_FAILED

**In simple words:**
You're trying to contact the wrong URL β†’ the server doesn't know it β†’ doesn't respond properly β†’ browser blocks it due to CORS.

βœ… **Correct solution for your case:**

In your code (probably in your `fetch` or Apollo setup or whatever GraphQL client you are using),
**update the endpoint** from:

- https://wprock.ddev.site/graphql
+ https://wprock.ddev.site/wp/graphql

Example if using `fetch`:

fetch('https://wprock.ddev.site/wp/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: `{
      menu(id: "primary", idType: LOCATION) {
        menuItems {
          nodes {
            label
            url
          }
        }
      }
    }`
  })
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));

Or if you’re using Apollo Client setup:

const client = new ApolloClient({
  uri: 'https://wprock.ddev.site/wp/graphql', // Correct URL
  cache: new InMemoryCache(),
});

πŸ›  **Also important:**
If you are using **DDEV** + **Vite** in dev mode (`https://wprock.ddev.site:5173` β†’ frontend)
**and** your WordPress (`https://wprock.ddev.site` β†’ backend),
then to avoid future CORS issues, you can also install a simple plugin like:

– βœ… [WP-CORS plugin](https://wordpress.org/plugins/wp-cors/)
– or add in your WordPress `functions.php`:

add_action( 'init', function() {
    if ( strpos( $_SERVER['HTTP_ORIGIN'] ?? '', 'wprock.ddev.site' ) !== false ) {
        header( 'Access-Control-Allow-Origin: https://wprock.ddev.site:5173' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS' );
        header( 'Access-Control-Allow-Headers: *' );
    }
});

This way WordPress will allow requests from your Vite dev server while developing.

Would you like me to also show you a **full working example** for fetching your WordPress Primary Menu from `wp/graphql`? πŸš€
(very quick, just 10 lines)

User
onlive it gives
Error loading menu: Unexpected token '
Assistant
Perfect, you're very close now β€” I know **exactly** what's happening.

πŸ‘‰ **This error:**

Error loading menu: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

means that **instead of JSON**, your request to `https://wprock.ddev.site/wp/graphql` is receiving **an HTML page**.

Normally, when you see:

"<!DOCTYPE html>..."

it means **you hit a 404 page, a login page, or some error page** β€” not actual GraphQL data.

πŸ” **Root Causes Possible:**
| Problem | Why it happens |
|:—|:—|
| Wrong URL | `wp/graphql` endpoint is not there on live |
| GraphQL plugin not installed | Your live WordPress site may be missing WPGraphQL plugin |
| Permalinks | WordPress permalinks may not be flushed yet |
| SSL/HTTP mismatch | HTTPS redirect or SSL cert issue |
| Security plugins/firewall | Some plugins or server settings block POST request |

βœ… **Quick checklist to solve it:**

1. **Check if WPGraphQL is active on live:**
Go to your live site's `/wp-admin/plugins.php` and make sure **WPGraphQL plugin** is installed and active.
If missing, install [WPGraphQL](https://wordpress.org/plugins/wp-graphql/).

2. **Manually visit the GraphQL endpoint in browser:**
Open browser and go to:
πŸ‘‰ `https://your-live-site.com/wp/graphql`
If it shows a JSON like:

{"errors":[{"message":"Must provide query string."}]}

βœ… It's working.

If you see a **404 page or login page**, ❌ then WPGraphQL is not active or permalinks are wrong.

3. **Flush Permalinks (Resave Settings):**
Even if plugin is active, sometimes you need to **resave permalinks**:
– Go to WordPress Admin β†’ Settings β†’ Permalinks β†’ just click **Save Changes** (no changes needed).
This rebuilds the rewrite rules.

4. **If still getting HTML instead of JSON:**
Check if you are being redirected (maybe HTTPS or login redirect).
– Maybe your live GraphQL endpoint is protected.
– Maybe live server forces redirects that confuse your frontend.

Use browser **Network tab** β†’ See the actual Response.

πŸ›  **Important tip:**
In your React code, you can also add a **catch** to detect HTML response errors easily:

fetch('https://your-live-site.com/wp/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: `{
      menu(id: "primary", idType: LOCATION) {
        menuItems {
          nodes {
            label
            url
          }
        }
      }
    }`
  })
})
.then(async (res) => {
  const text = await res.text();
  try {
    return JSON.parse(text);
  } catch (err) {
    console.error('Server returned non-JSON response:', text);
    throw new Error('Invalid JSON');
  }
})
.then(data => console.log('Menu Data:', data))
.catch(err => console.error('Error loading menu:', err));

This will **print the full wrong HTML** in console so you can see if it's a 404, login page, or something else.

**Summary:**

| Step | Action |
|:—|:—|
| 1 | Check WPGraphQL plugin installed and activated on live |
| 2 | Manually check `https://your-live-site.com/wp/graphql` |
| 3 | Resave permalinks |
| 4 | Check if request is redirected |
| 5 | Improve fetch error handling to debug response |

Would you like me to also show you **how to protect fetch** if it **accidentally hits a login page** (example auto-logout protection)? πŸ”₯
Let me know! πŸš€

Leave a Comment

Your email address will not be published. Required fields are marked *