Tricks — req.is(type) in ExpressJS

Written by new | Published 2016/06/12
Tech Story Tags: nodejs | javascript | expressjs

TLDRvia the TL;DR App

Today I learned a new trick. The req.is method.

On every Express request object there is a method called is that allows you to check if the incoming request’s “Content-Type” HTTP header is a certain mime type.

If you want to check the mime of a request, just use the method as so:

var express = require(‘express’);
var app = express();

// listening for post requests on the root.
app.post(‘/’, (req, res, next) => {
    console.log(
        req.is(‘*/*’),

        req.is(‘text/*’),

        req.is(‘*/html’),

        req.is(‘json’),

        req.is(‘*/json’)
    );

    res.sendStatus(200);
});

app.listen(3300);

If you put the above snippet in a file index.js and run it with node index.js (you’ll need to have the express package installed), and then make the following curl request:

curl http://localhost:3300 -H “Content-Type: application/json” -d ‘body’

You’ll get the following output:

req.is(‘*/*’) --> 'application/json'

req.is(‘text/*’) --> false

req.is(‘*/html’) --> false

req.is(‘json’) --> 'json'

req.is(‘*/json’) --> 'application/json'

On changing the content-type to text/html, you get:

req.is(‘*/*’) --> 'text/html'

req.is(‘text/*’) --> 'text/html'

req.is(‘*/html’) --> 'text/html'

req.is(‘*/json’) -->  false

It’s pretty simple to see what’s happening here. If the content-type matches on the extension name (json) or a mime type (application/json) or a mime type wildcard (*/json), that name/mime type will be returned.

The method accepts an array of inputs or multiple inputs (which then get picked from arguments and pushed into an array) and returns the first matching input against the content-type or false.

So with incoming content-type set to text/html:

req.is(‘text/html’, 'text') --> 'text/html'

But:

req.is(‘text’, 'text/html') --> 'text'

All this functionality comes from Express’s usage of the type-is library.

Pretty neat stuff.


Published by HackerNoon on 2016/06/12