Declare JSON responses
An endpoint returns JSON and needs an explicit JSON media type.
Express.js · Module
Sets the response Content-Type from a MIME type or file extension. Values containing / are used literally; other values undergo extension-based MIME lookup.
res.type(type) sets the response’s Content-Type. A value containing / is used directly; otherwise Express treats it as a file extension and looks up the corresponding MIME type.
res.type(type)| Name | Type | Description |
|---|---|---|
type | String | A MIME type or a file extension used to determine the response Content-Type. |
Response
/ are interpreted as extensions rather than literal media types.const express = require('express');
const app = express();
app.get('/data', (req, res) => {
res.type('json').send({ ok: true });
});
app.listen(3000);Sets the response MIME type to JSON before sending the payload.
An endpoint returns JSON and needs an explicit JSON media type.
A route serves content whose format is identified by a known extension.
An API must emit a vendor-specific or other custom media type.
It accepts a MIME type or an extension and returns the response object. Extensions are resolved through Express’s MIME mapping, while values containing / are applied literally.
Follow-up: What does res.type('json') do? It looks up the JSON MIME type and sets the Content-Type accordingly.
res.type('.html') and res.type('html') both select the HTML MIME type. The leading dot is optional for extension lookup.
Follow-up: How would you set a custom media type? Pass the complete value, such as application/vnd.example+json, because it contains /.
The method changes the response Content-Type header and returns res, allowing response methods to be chained. It does not itself send the response.
Follow-up: Why might setting the type before send() matter? The later body-sending operation can use the selected type when constructing the HTTP response.
res.set()res.get()res.send()express.static.mime.lookup()