修改json-server自定义路由响应类型时遇NotAcceptableError报错求助
解决json-server自定义路由返回text/plain时的NotAcceptableError错误
问题出在res.format的MIME类型写法上,你错误地给类型字符串加上了content-type:前缀,导致无法匹配请求的Accept头部,从而抛出NotAcceptableError。
修正方案1:修正res.format的MIME类型键
将'content-type: text/plain'改为纯MIME类型字符串'text/plain',同时优化错误处理(返回500状态码更符合HTTP规范):
server.get('/static/*', (req, res) => { const filePath = path.join(__dirname, `myfile.md`); fs.readFile(filePath, 'utf8', (err, data) => { if (err) { res.status(500).send(err.message); return; } res.format({ 'text/plain': () => res.send(data) }); }); });
修正方案2:更简洁的写法(推荐)
因为你只需要返回text/plain一种类型,没必要使用res.format,直接设置响应类型并发送数据即可:
server.get('/static/*', (req, res) => { const filePath = path.join(__dirname, `myfile.md`); fs.readFile(filePath, 'utf8', (err, data) => { if (err) { res.status(500).send(err.message); return; } res.type('text/plain').send(data); }); });
错误原因说明
res.format会根据请求的Accept头部,匹配你传入的对象中的MIME类型键。你原来写的'content-type: text/plain'不是合法的MIME类型标识,没有可匹配的项时,Express就会抛出NotAcceptableError。
内容的提问来源于stack exchange,提问作者Sergino
相关产品推荐
相关产品推荐

