Angular 4 调用 couchdb 有 CORS 错误,但在小提琴手中没有显示预检



我有一个用 Angular 4 编写的应用程序,在本地主机上调用一个 couchdb,但端口不同。

我一直在将couchdb与Aurelia应用程序一起使用,没有任何问题。

现在我正在切换到 Angular 4 和 Angular MD,我似乎可以通过这个 cors 问题。

这是调用 Couchdb 的代码

private commonUpdate(content: any, url: string, method: string = "放"( {

console.log("in common")
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: myHeaders, withCredentials: true });
if (content && content._rev && content._rev.length >= 5) {
url = url + '/' + content._id;
}
const status = new DbStatus();
status.ok = false;
let response: any;
try {
if (content) {
const contentJson: string = JSON.stringify(content);
this.http.post(url, contentJson, options).map(res => res.json()).subscribe(data => {
console.log(data['results']);
})
} 
status.ok = this.isHttpStatusSuccess(response.status);
if (status.doc) {
if (Array.isArray(status.doc.docs)) {
if (status.doc.docs.length === 0) {
status.ok = false;
status.reason = 'Empty Array';
if (!status.error) status.error = status.reason;
}
}
}
status.httpStatus = response.status;
status.response = response;
} catch (error) {
status.ok = false;
}

错误消息:

VM27427:1 XMLHttpRequest 無法載入 localhost:5984/_session。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

[cors] 
origins = *
credentials = true
headers = accept, authorization, content-type, origin, referer
Couch-Rev, Set-Cookie
methods = GET, PUT, POST, HEAD, DELETE

我不明白为什么这确实有效。 同样,小提琴手不显示印前检查 OPTION 方法请求。

但是,从邮递员运行 OPTION 方法会返回允许的 GET 和 HEAD 方法。 也许浏览器正在缓存它,但我打开了开发工具并选中了缓存禁用设置。

建议

VM27427:1 XMLHttpRequest 无法加载 localhost:5984/_session。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

这听起来问题只是您在代码中提供给this.http.post调用的 URL 没有协议部分——也就是说,您只为调用提供localhost:5984/_session,但您应该http://localhost:5984/_session它。您只需添加http://

因此,至于为什么您没有看到OPTIONS请求,我想这只是因为浏览器在尝试OPTIONS之前就停止了 - 因为URL中没有协议部分,浏览器甚至无法确定您提供的URL是否是跨源的。

最新更新