使用node-fetch调用CouchDB _bulk_get返回415错误的排查求助
解决CouchDB _bulk_get接口返回415 Unsupported Media Type的问题
先直接给你结论:导致415错误的核心原因是你的请求缺少了Content-Type: application/json请求头,和include_docs参数、请求体格式无关,下面详细拆解:
1. 为什么会返回415?
CouchDB的_bulk_get接口接收POST请求时,要求请求体是JSON格式,必须通过请求头明确告诉服务器“我发的是JSON数据”。你代码里虽然用JSON.stringify把请求体转成了JSON字符串,但如果this.headers里没有包含Content-Type: application/json,服务器无法识别请求体的格式,就会直接返回415错误。
2. 关于你疑问的几个点
include_docs=true是完全合法的:这个参数是_bulk_get接口的标准参数,用来返回完整的文档内容,绝对不是导致415的原因,放心用。- 请求体格式没问题:你传的
{ keys: ids }完全符合CouchDB对_bulk_get接口的请求体要求,格式上没有错误。
3. 修复方案
只需要在请求头里添加Content-Type: application/json即可,修改后的代码示例如下:
public getDocuments(databaseName: string, ids: string[]): Promise<ICouchDBDocumentDoc[]> { return fetch(`${this.baseUrl}/${databaseName}/_bulk_get?include_docs=true`, { headers: { ...this.headers, // 保留原有headers 'Content-Type': 'application/json' // 添加这个关键请求头 }, method: 'POST', body: JSON.stringify({ keys: ids }), }) .then((response) => { return this.responseHandler(response); }) .then((response) => { console.log('docs'); console.log(JSON.stringify(response, null, 4)); return response; }); }
另外可以顺便检查一下this.headers里有没有不小心设置了错误的Content-Type(比如text/plain),如果有的话也要同步修正。
内容的提问来源于stack exchange,提问作者user1283776
相关产品推荐
相关产品推荐

