POST blocked by CORS even though I specified in the headers

In my worker script, I allowed any origin to get or post like so:

const headers = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
  "Access-Control-Max-Age": "86400",
  'Content-type': 'application/json'
}

Although my get works, when I tried to post, I got:

localhost/:1 Access to fetch at ‘https://worker.username.workers.dev/’ from origin ‘http://localhost:3002’ has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Why? 

Thank you!

What does your code look like?

Here’s part of it

async function postNew (request){
  const body = await request.text()
  try{
    let parseBody = JSON.parse(body)
    KV.put(parseBody["id"],body)
    return new Response('success', {headers})}
  catch(err){
    return new Response("There's an error posting: " + err, {headers})
  }
}

async function handleRequest(request) {
  if (request.method === 'POST') {
    return postNew(request)
  } else {
    ...
  }
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

and here’s the code from my React App

   async function submitPost(){
  
        const resp = await fetch("https://worker.username.workers.dev", 
        { 
            method: 'POST', 
            body: JSON.stringify({someData}),
            headers: { 'Content-type': 'application/json' }
        }
        )
        return new Response(`success: ${resp.json()}`)
        }

I forgot to reply to you directly, but I pasted my code below. thank you so much:)

It looks like your CORS headers are not being applied to the Preflight header which is the options header that first comes.

Checkout out this example:

https://developers.cloudflare.com/workers/examples/cors-header-proxy

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.