在 CouchDB 上进行预检的 CORS 请求

CORS requests with preflight on CouchDB

我们正在尝试向 CouchDB 发送 HTTP 跨域请求。

为实现这一点,我们使用以下设置设置 CouchDB(灵感来自 add-cors-to-couchdb tool):

[HTTPD]
enable_cors = true

[CORS]
origins = *
credentials = true
methods = GET, PUT, POST, HEAD, DELETE
headers = accept, authorization, content-type, origin, referer, x-csrf-token

并编写了与此类似的代码(当然不是硬编码):

<html>
  <body>
    <script>
      fetch("http://acme.org:5984/mydb/323958d9b42be0aaf811a3c96b4e5d9c", {
        method: 'DELETE',
        headers: {'If-Match': "1-0c2099c9793c2f4bf3c9fd6751e34f95"}
      }).then(x => {
        if (x.ok) return x.json().then(console.log);
        console.error(x.statusText);
      });
    </script>
   </body>
 </html>

虽然它在 GETPOST 上工作正常,但我们在 DELETE 上得到 405 Method not allowed。浏览器告诉预检响应(对 OPTIONS 请求)不成功,而服务器指示 {"error":"method_not_allowed","reason":"Only DELETE,GET,HEAD,POST,PUT,COPY allowed"}.

我们尝试了 CouchDB 2.1.1 和 1.6.1。我们还尝试将 origins: * 替换为 origins: http://localhost:8080(其中 8080 是服务于上述 HTML 的端口)。我们还尝试将 credentials 设置为 false

a comment by @Ingo Radatz到一个相关问题,我终于明白了请求中使用的EVERYheader必须包含在CouchDB CORS设置中。

就我个人而言,我必须在接受的 header 中包含 if-match

[HTTPD]
enable_cors = true

[CORS]
origins = *
methods = GET, PUT, POST, HEAD, DELETE
headers = accept, authorization, content-type, origin, referer, if-match