- When in doubt, use
.send()
. It dynamically setsContent-Type
headers to match the data it sends. - When sending JSON, you can either use
.json()
uses.send()
..json()
is arguably 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.
Last active
May 19, 2024 15:56
-
-
Save acidtone/df91c6276e69ae3726e3f8b39223ceec to your computer and use it in GitHub Desktop.
Express: send() vs json() vs end()
This file contains 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 | |
app.get('/json/html',(req, res) => { | |
res.json('<p>hello world</p>'); | |
}) | |
/***********/ | |
/* .end() */ | |
/***********/ | |
// Text --> No `Content-Type` | |
app.get('/end/text',(req, res) => { | |
res.end('hello world'); | |
}); | |
// HTML --> No `Content-Type` | |
app.get('/end/html',(req, res) => { | |
res.end('<p>hello world</p>'); | |
}); | |
// JSON --> text/html | |
app.get('/end/json',(req, res) => { | |
res.end({hello: 'world'}); | |
}); | |
const PORT = process.env.PORT || 3000 | |
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