【问题标题】:Why isn't express-js setting the Content-Type header?为什么 express-js 不设置 Content-Type 标头?
【发布时间】:2011-07-21 00:31:29
【问题描述】:

我有以下几点:

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 引起的

【问题讨论】:

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


    【解决方案1】:

    试试这个代码:

    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】:

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

    【讨论】:

    • 这很棒,因为它仍然允许您使用 res.send(obj) 将对象作为 JSON 发送。优于res.end(JSON.stringify(obj))
    • 你也可以链接它,res.type('json').send({your: 'object'}); 或下面的@danday74 指出,只需res.json({your: 'object'});
    【解决方案3】:

    而不是res.send()

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

    【讨论】:

    • 这并不能远程回答问题
    • 与问题无关。
    • 就我而言,这正是问题所在:Why isn't express-js setting the Content-Type header? 在我的情况下是 json。我了解了res.json()
    猜你喜欢
    • 1970-01-01
    • 2013-12-10
    • 2015-05-05
    • 1970-01-01
    • 2021-12-22
    • 2013-07-22
    • 2012-05-27
    相关资源
    最近更新 更多