【问题标题】:Angular 4 call couchdb has CORS error, but no preflight shows up in fiddlerAngular 4 call couchdb有CORS错误,但提琴手中没有出现预检
【发布时间】:2018-01-05 20:08:11
【问题描述】:

我有一个用 Angular 4 编写的应用程序,它在 localhost 但不同的端口上调用了一个 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 方法请求。

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

建议

【问题讨论】:

    标签: angular xmlhttprequest cors couchdb preflight


    【解决方案1】:

    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 是否是跨域的。

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2017-05-18
      • 2018-07-31
      • 2022-01-23
      • 1970-01-01
      • 2021-03-01
      • 2022-01-06
      • 2018-08-16
      • 1970-01-01
      相关资源
      最近更新 更多