Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active May 19, 2024 15:56
Show Gist options
  • Save acidtone/df91c6276e69ae3726e3f8b39223ceec to your computer and use it in GitHub Desktop.
Save acidtone/df91c6276e69ae3726e3f8b39223ceec 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() 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 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
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