为什么express-js不设置Content-Type标头?

时间:2011-03-23 03:59:02

标签: javascript node.js http-headers express offline-caching

我有以下内容:

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);

Chrome中的网络标签显示为text/plain。为什么不设置标题?

上面的代码有效,我的问题是由链接到旧版本的express-js引起的

3 个答案:

答案 0 :(得分:38)

res.type('json')现在也有效,正如其他人所说,你可以简单地使用
 res.json({your: 'object'})

答案 1 :(得分:19)

试试这段代码:

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);

(我假设您使用的是Express的最新版本,2.0.0)

<强>更新 我刚刚使用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

请确保在尝试之前清除缓存。

答案 2 :(得分:0)

而不是res.send()

使用res.json()自动将内容类型设置为application/json