Why isn't express-js setting the Content-Type header?
Asked Answered
M

3

30

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?

The code above works, my problems were caused by a linking to an old version of express-js

Master answered 23/3, 2011 at 3:59 Comment(0)
G
47

res.type('json') works too now and as others have said, you can simply use
res.json({your: 'object'})

Guileless answered 23/10, 2016 at 20:43 Comment(2)
this is great since it still allows you to use res.send(obj) to send objects as JSON. Better than res.end(JSON.stringify(obj))Endamoeba
you can chain it too, res.type('json').send({your: 'object'}); or as @danday74 below points out, simply res.json({your: 'object'});Prohibit
H
24

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)

UPDATE: I just did a quick test using Firefox 3.6.x and Live HTTP Headers. This is the addons output:

 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.

Hatshepsut answered 23/3, 2011 at 7:5 Comment(2)
i just tested it on my local development setup, worked perfectly (see update)Hatshepsut
Aha! For some reason it was linking to an old version of node. Thank you! :)Master
P
2

instead of res.send()

use res.json() which automatically sets the content-type to application/json

Poem answered 5/2, 2018 at 9:53 Comment(3)
this doesn't remotely answer the questionFlutist
Not related to the question.Her
In my case, it was exactly the question : Why isn't express-js setting the Content-Type header? in my case to json. I learned about res.json()Regeneration

© 2022 - 2024 — McMap. All rights reserved.