如何使用 HttpClient 从 Angular 将文档上传到 CouchDB

How to upload documents to CouchDB from Angular using HttpClient

我在我的本地计算机上设置了一个新的 CouchDB。当我尝试使用 HTTP POST 方法将新文档上传到现有数据库时,CouchDB 拒绝请求并声称它是 HTTP OPTIONS 方法。

Typescript classes

我的服务 class 如下所示。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DbService {

    private static readonly BASE_URL = 'http://localhost:5984/';
    private static readonly ENTRIES_URL = DbService.BASE_URL + 'entries';

    constructor(private http: HttpClient) { }

    writeEntry(entry: Object): Promise<Object> {
        return this.http.post<Object>(DbService.ENTRIES_URL, entry).toPromise();
    }
}

该服务由以下方法使用,位于组件 class。

private onEntry(entry: Object): void {
    try {
         console.log('onEntry', entry);
         this.dbService.writeEntry(entry)
             .then(r => console.log(r))
             .catch(e => console.error(e));
    } catch (error) {
        console.error(error);
    }
}

到目前为止我尝试了什么

  1. 我使用 Fauxton 创建了一个名为 entries
  2. 的新数据库
  3. 我使用 curl 成功将新文档上传到 entries 数据库,如下所示
    curl -H 'Content-Type: application/json' -X POST 
    http://127.0.0.1:5984/entries -d '{ "amount": 1 }' 
    
  4. 当运行 Angular 代码(ng serve & Chrome 浏览器)
    • 我看到控制台日志信息(在服务调用之前),然后是错误日志。
    • CouchDB 记录以下内容(不允许使用 405 方法)
      [notice] 2019-04-09T06:03:26.304000Z couchdb@localhost  00d60c0651 localhost:5984 127.0.0.1 undefined OPTIONS /entries 405 ok 7  
      

最后一次尝试

按如下方式更改我的服务方法时,POST 方法最终被传输到网络,但 CouchDB 记录了 HTTP 415(不支持的媒体类型)

writeEntry(entry: Object): Promise<Object> {
    const httpHeaders = new HttpHeaders();
    httpHeaders.set('Accept', 'application/json');
    httpHeaders.set('Content-type', 'application/json');
    const httpOptions = {
      headers: httpHeaders
    };
    return this.http.post<Object>(DbService.ENTRIES_URL, JSON.stringify(entry), httpOptions).toPromise();
} 
[notice] 2019-04-09T13:35:59.312000Z couchdb@localhost  9910b3c996 localhost:5984 127.0.0.1 undefined POST /entries 415 ok 3

这可能与 CORS 问题有关。

尝试在 CouchDB HTTP 服务器中启用 CORS:https://docs.couchdb.org/en/stable/config/http.html#config-cors

此功能内置于 https://issues.apache.org/jira/browse/COUCHDB-431