nodejs & express 4, res.json 返回“Content-Type: text/plain”

jus*_*ser 3 node.js express

我试图让我的应用程序返回“application/json”作为内容类型,当然只要响应是 json。

我试过了:

res.json(jsonContent);

response header has "Content-Type ? text/plain; charset=utf-8"
Run Code Online (Sandbox Code Playgroud)

res.setHeader('content-type', 'text/json');
res.send(jsonContent); 

response header has "Content-Type ? text/plain; charset=utf-8"
Run Code Online (Sandbox Code Playgroud)

res.set('content-type', 'text/json');
res.send(jsonContent); 

response header has "Content-Type ? text/plain; charset=utf-8"
Run Code Online (Sandbox Code Playgroud)

并且同时进行以上所有操作。但是我的应用程序总是将响应作为文本/纯文本而不是应用程序/json。我可能做错了什么?

Ash*_*y B 5

正如文档解释的那样:

res.type('json');               // => 'application/json'
res.type('application/json');   // => 'application/json'
Run Code Online (Sandbox Code Playgroud)

将 Content-Type HTTP 标头设置为指定类型。


Jay*_*den 3

根据您的设置(和应用的中间件),如果客户端的请求不是使用 Accept: application/json 发出的,则响应的内容类型可能会设置为 text/plain。