【问题标题】:How to upload documents to CouchDB from Angular using HttpClient如何使用 HttpClient 从 Angular 将文档上传到 CouchDB
【发布时间】:2019-04-09 07:03:20
【问题描述】:

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

Typescript 类

我的服务类如下所示。

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();
    }
}

服务由以下方法使用,位于组件类中。

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. 我使用 curl 成功将新文档上传到 entries 数据库,如下所示 curl -H '内容类型:应用程序/json' -X POST http://127.0.0.1:5984/entries -d '{ "amount": 1 }'
  3. 运行 Angular 代码时(ng serve 和 Chrome 浏览器)
    • 我看到控制台日志信息(在服务调用之前),然后是错误日志。
    • CouchDB 记录以下内容(不允许使用 405 方法) [通知] 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();
} 
[通知] 2019-04-09T13:35:59.312000Z couchdb@localhost 9910b3c996 localhost:5984 127.0.0.1 undefined POST /entries 415 ok 3

【问题讨论】:

    标签: angular couchdb angular7


    【解决方案1】:

    这可能与 CORS 问题有关。

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

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

    【讨论】:

    • 在 etc\local.ini 中定义 [cors] 后现在可以工作,并且不再对提交的 JSON 对象进行字符串化,感谢您的帮助! [cors]\n 来源 = * 方法 = GET、POST、PUT 凭据 = false
    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2010-10-04
    相关资源
    最近更新 更多