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

前端 未结 4 1541
耶瑟儿~
耶瑟儿~ 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 13:58

    Please define "not working as they should", because they do for me.

    In other words:

    // server.js
    console.log('Accepts JSON?', req.accepts('json') !== undefined);
    
    // client sends 'Accept: application/json ...', result is:
    Accepts JSON? true
    
    // client sends 'Accept: something/else', result is:
    Accepts JSON? false
    

    The Content-Type header as sent by a client isn't used for content negotiation, but to declare the content type for any body data (like with a POST request). Which is the reason why req.is() isn't the correct method to call in your case, because that checks Content-Type.

提交回复
热议问题