- When in doubt, use
.send()
. It dynamically setsContent-Type
headers to match the data it sends. - When sending JSON, you can either use
.json()
or.send()
..json()
is likely less confusing.json()
uses.send()
under the hood so the resulting HTTP headers are the same.
.json()
has JSON formatting options (replacer
andspace
) that you'll probably never need.- Only use
.end()
when you need to end theresponse
without providing data..send()
/.json()
will end theresponse
after they send data anyway.
-
-
Save gregfenton/a32df81a3febfadcdce3acd8934d0c18 to your computer and use it in GitHub Desktop.
Express: send() vs json() vs end()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
/***********/ | |
/* .send() */ | |
/***********/ | |
// Text -> text/html | |
app.get('/send/text',(req, res) => { | |
res.send('hello world'); | |
}); | |
// HTML -> text/html | |
app.get('/send/html',(req, res) => { | |
res.send('<p>hello world</p>'); | |
}); | |
// JSON -> application/json | |
app.get('/send/json',(req, res) => { | |
res.send({hello: 'world'}); | |
}); | |
/***********/ | |
/* .json() */ | |
/***********/ | |
// JSON -> application/json | |
app.get('/json/json',(req, res) => { | |
res.json({hello: 'world'}); | |
}) | |
// HTML -> application/json -- this is strange | |
app.get('/json/html',(req, res) => { | |
res.json('<p>hello world</p>'); | |
}) | |
/***********/ | |
/* .end() */ | |
/***********/ | |
// Text --> No `Content-Type` -- strange | |
app.get('/end/text',(req, res) => { | |
res.end('hello world'); | |
}); | |
// HTML --> No `Content-Type` -- strange, don't do this | |
app.get('/end/html',(req, res) => { | |
res.end('<p>hello world</p>'); | |
}); | |
// JSON --> text/html -- strange, don't do this | |
app.get('/end/json',(req, res) => { | |
res.end({hello: 'world'}); | |
}); | |
const PORT = process.env.PORT || 4000 | |
app.listen(PORT, function(){ | |
console.log(`Listening on port ${PORT}.`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment