【发布时间】: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);
}
}
到目前为止我尝试了什么
- 使用 Fauxton,我创建了一个名为 entries 的新数据库
- 我使用 curl 成功将新文档上传到 entries 数据库,如下所示 curl -H '内容类型:应用程序/json' -X POST http://127.0.0.1:5984/entries -d '{ "amount": 1 }'
- 运行 Angular 代码时(ng serve 和 Chrome 浏览器)
最后一次尝试
如下更改我的服务方法时,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
【问题讨论】: