NodeJS : Validating request type (checking for JSON or HTML)

前端 未结 4 1525
耶瑟儿~
耶瑟儿~ 2020-12-16 13:32

I would like to check if the type that is requested by my client is JSON or HTML, as I want my route to satisfy both human and machine needs.

I have read the Express

4条回答
  •  一生所求
    2020-12-16 14:07

    To throw my hat in the ring, I wanted easily readable routes without having .json suffixes everywhere or having to have each route hide these details in the handler.

    router.get("/foo", HTML_ACCEPTED, (req, res) => res.send("

    baz

    qux

    ")) router.get("/foo", JSON_ACCEPTED, (req, res) => res.json({foo: "bar"}))

    Here's how those middlewares work.

    function HTML_ACCEPTED (req, res, next) { return req.accepts("html") ? next() : next("route") }
    function JSON_ACCEPTED (req, res, next) { return req.accepts("json") ? next() : next("route") }
    

    Personally I think this is quite readable (and therefore maintainable).

    $ curl localhost:5000/foo --header "Accept: text/html"
    

    baz

    qux

    $ curl localhost:5000/foo --header "Accept: application/json" {"foo":"bar"}

    Notes:

    • I recommend putting the HTML routes before the JSON routes because some browsers will accept HTML or JSON, so they'll get whichever route is listed first. I'd expect API users to be capable of understanding and setting the Accept header, but I wouldn't expect that of browser users, so browsers get preference.
    • The last paragraph in ExpressJS Guide talks about next('route'). In short, next() skips to the next middleware in the same route while next('route') bails out of this route and tries the next one.
    • Here's the reference on req.accepts.

提交回复
热议问题