如何使用HttpClient从Angular将文档上传到CouchDB [英] How to upload documents to CouchDB from Angular using HttpClient
问题描述
我在本地计算机上设置了一个新的CouchDB.当我尝试使用HTTP POST方法将新文档上传到现有数据库时,CouchDB拒绝了该请求,并声称这是HTTP OPTIONS方法.
I set up a new CouchDB on my local computer. When I try to upload new documents to an existing database using HTTP POST method, CouchDB refuses the request and claims it was HTTP OPTIONS method.
打字稿类
我的服务类别如下.
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();
}
}
该服务由位于组件类中的以下方法使用.
The service is used by the following method, located in a component 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);
}
}
到目前为止我尝试过的事情
- 使用Fauxton,我创建了一个名为 entries 的新数据库.
- 我使用curl成功将新文档上传到 entries 数据库,如下所示
- Using Fauxton, I created a new database named entries
- I successfully uploaded new documents to the entries database using curl as follows
curl -H 'Content-Type: application/json' -X POST
http://127.0.0.1:5984/entries -d '{ "amount": 1 }'
- 我看到控制台日志信息(在服务呼叫之前),然后是错误日志.
- CouchDB记录以下内容(不允许使用405方法)
- When running the Angular code (ng serve & Chrome Browser)
- I see the console log info (before service call), followed by the error log.
- CouchDB logs the following (405 Method not allowed)
[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(不受支持的媒体类型)
When changing my service method as follows, the POST method is finally carried on to the wire but CouchDB logs an HTTP 415 (Unsupported Media Type)
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问题有关.
This might have to do with CORS issues.
尝试在CouchDB HTTP服务器中启用CORS: https://docs.couchdb.org/en/stable/config/http.html#config-cors
Try enabling CORS in the CouchDB HTTP Server: https://docs.couchdb.org/en/stable/config/http.html#config-cors
此功能内置于 https://issues.apache.org/jira/browse/COUCHDB-431
这篇关于如何使用HttpClient从Angular将文档上传到CouchDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!