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

前端 未结 4 1529
耶瑟儿~
耶瑟儿~ 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:02

    var requestType = req.get('Content-Type'); definitely works if a content-type was actually specified in the request (I just re-verified this a minute ago). If no content-type is defined, it will be undefined. Keep in mind that typically only POST and PUT requests will specify a content type. Other requests (like GET) will often specify a list of accepted types, but that's obviously not the same thing.

    EDIT:

    Okay, I understand your question better now. You're talking about the Accept: header, not content-type.

    Here's what's happening: notice the */*;q=0.8 at the end of listed accept types? That essentially says "I'll accept anything." Therefore, req.accepts('json') is always going to return "json" because technically it's an accepted content type.

    I think what you want is to see if application/json is explicitly listed, and if so, respond in json, otherwise respond in html. This can be done a couple of ways:

    // a normal loop could also be used in place of array.some()
    if(req.accepted.some(function(type) {return type.value === 'application/json';}){
        //respond json
    } else {
        //respond in html
    }
    

    or using a simple regular expression:

    if(/application\/json;/.test(req.get('accept'))) {
        //respond json
    } else {
        //respond in html
    }
    

提交回复
热议问题