Skip to content

Instantly share code, notes, and snippets.

@gregfenton
Forked from acidtone/README.md
Last active March 10, 2023 17:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregfenton/a32df81a3febfadcdce3acd8934d0c18 to your computer and use it in GitHub Desktop.
Save gregfenton/a32df81a3febfadcdce3acd8934d0c18 to your computer and use it in GitHub Desktop.
Express: send() vs json() vs end()

Express: res.send() vs res.json() vs res.end()

Materials

Key Takeaways

  • When in doubt, use .send(). It dynamically sets Content-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 and space) that you'll probably never need.
  • Only use .end() when you need to end the response without providing data.
    • .send()/.json() will end the response after they send data anyway.
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