Javascript 为什么 express-js 不设置 Content-Type 标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5400761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why isn't express-js setting the Content-Type header?
提问by Kit Sunde
I have the following:
我有以下几点:
var express = require('express'),
app = express.createServer();
app.get("/offline.manifest", function(req, res){
res.contentType("text/cache-manifest");
res.end("CACHE MANIFEST");
});
app.listen(8561);
The network tab in Chrome says it's text/plain
. Why isn't it setting the header?
Chrome 中的网络选项卡说它是text/plain
. 为什么不设置标题?
The code above works, my problems were caused by a linking to an old version of express-js
上面的代码有效,我的问题是由链接到旧版本的 express-js 引起的
回答by Ray Hulha
res.type('json')
works too now and as others have said, you can simply useres.json({your: 'object'})
res.type('json')
现在也可以使用,正如其他人所说,您可以简单地使用res.json({your: 'object'})
回答by schaermu
Try this code:
试试这个代码:
var express = require('express'),
app = express.createServer();
app.get("/offline.manifest", function(req, res){
res.header("Content-Type", "text/cache-manifest");
res.end("CACHE MANIFEST");
});
app.listen(8561);
(I'm assuming you are using the latest release of express, 2.0.0)
(我假设您使用的是最新版本的 express,2.0.0)
UPDATE:I just did a quick test using Firefox 3.6.x and Live HTTP Headers. This is the addons output:
更新:我刚刚使用 Firefox 3.6.x 和 Live HTTP Headers 做了一个快速测试。这是插件输出:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/cache-manifest
Connection: keep-alive
Transfer-Encoding: chunked
Make sure you clear your cache before trying.
在尝试之前,请确保清除缓存。
回答by danday74
instead of res.send()
代替 res.send()
use res.json()
which automatically sets the content-type to application/json
使用res.json()
它自动将内容类型设置为application/json