Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch PATCH request not allowed (CORS)

So I've been using fetch for quite a while without any issues. I've created plenty of APIs and had to implement CORS in multiple APIs.

However, today I can't seem to get CORS to work for a single patch request. It works for get/post/delete without issues, but patch isn't working.

I have read fetch patch request is not allowed, and sadly I already wrote patch fully capitalized, so this isn't a solution for me.

My request:

{
  method: 'PATCH', //using POST here makes everything work fine.
  json: true,
  headers: defaultHeaders,
  body: JSON.stringify({
    type: 'analytics_analyzers',
    attributes: {
      status: active ? 1 : 2,
      ssid: getState().config.ssid
    }
  })
}

And the server's .htaccess file:

SetEnvIf Origin "http(s)?://(www\.)?    (whitelistUrl1|whitelistUrl2|whitelistUrl3)$" AccessControlAllowOrigin=$0
Header always set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header always set Access-Control-Allow-Credentials true

SetEnvIf Access-Control-Request-Headers ".*" AccessControlHeaders=$0
Header always set Access-Control-Allow-Headers: %{AccessControlHeaders}e env=AccessControlHeaders

SetEnvIf Access-Control-Request-Method ".*" AccessControlMethod=$0
Header always set Access-Control-Allow-Methods: %{AccessControlMethod}e env=AccessControlMethod

Options request Error message

Anyone has any ideas to what I'm doing wrong here?

like image 238
Ron Oudgenoeg Avatar asked Nov 09 '22 12:11

Ron Oudgenoeg


1 Answers

In fact, when we send a not simple cors request to server side, like DELETE/ PUT / PATCH, but not include POST/GET/HEAD,the browser will send a OPTIONS request (preflight) to server side then ask if it is support the METHOD/ORIGIN/HEADERS, so if you just specified the PATCH request allowed method is not enough.

It's my example codes, just for this question, may be not so grace,hope u never mind ...

app.patch('/cors', (req, res) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length,Server,Date,access-control-allow-methods,access-control-allow-origin");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS,PATCH");
  res.send('ok')
})

app.options('/*', (req, res) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length,Server,Date,access-control-allow-methods,access-control-allow-origin");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS,PATCH");
  res.send('send some thing whatever')
})

like image 51
BertieHuang Avatar answered Nov 14 '22 21:11

BertieHuang