英文:
CouchDB: JavaScript Fetch API Fails To Connects Due To CORS on localhost
问题
使用Chrome浏览器导航至127.0.0.1:5984,从couchdb服务器获得响应。
当我使用Chrome的JavaScript调用相同地址时,无论是http://127.0.0.1:5984还是http://localhost:5984,都会失败。
从'http://localhost:5984/'到' http://localhost:8080'的跨源请求在CORS策略下被阻止:
对预检请求的响应未通过访问控制检查:它没有HTTP ok状态。
couchdb服务器上的local.ini
文件为:
[chttpd]
enable_cors = true
[cors]
origins = *
credentials = true
methods = GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, PATCH
headers = accept, authorization, content-type, origin, referer, cache-control, x-requested-with, X-Couch-Id, X-Couch-Rev
我的fetch选项目前为:
{
"headers": {
"Content-Type": "application/json",
"method": "GET",
"credentials": "include",
"mode": "cors"
}
}
英文:
After more testing, the CORS issue surfaces only when I add the 'credentials': 'include'
header. ...?
Using Chrome browser I navigate to 127.0.0.1:5984 and get response from couchdb server.
When I call the same address using Chrome's JavaScript it fails for both http://127.0.0.1:5984 as well as http://localhost:5984.
Access to fetch at 'http://localhost:5984/' from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The local.ini
file on the couchdb box has:
[chttpd]
enable_cors = true
[cors]
origins = *
credentials = true
methods = GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, PATCH
headers = accept, authorization, content-type, origin, referer, cache-control, x-requested-with, X-Couch-Id, X-Couch-Rev
My fetch options currently have:
{
"headers": {
"Content-Type": "application/json",
"method": "GET",
"credentials": "include",
"mode": "cors"
}
}
答案1
得分: 1
"If you're making a CORS request which includes credentials, you cannot use origins = *
. According to the MDN Docs:
Note: When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.
So you need http://localhost:5984
and any other relevant host in your local.ini
. This issue isn't CouchDB specific, you need to explicitly specify the origins for any API to which you make a CORS request from the browser.
英文:
If you're making a CORS request which includes credentials, you cannot use origins = *
. According to the MDN Docs:
> Note: When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.
So you need http://localhost:5984
and any other relevant host in your local.ini
. This issue isn't CouchDB specific, you need to explicitly specify the origins for any API to which you make a CORS request from the browser.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论