NodeJS:验证请求类型(检查JSON或HTML) [英] NodeJS : Validating request type (checking for JSON or HTML)

查看:148
本文介绍了NodeJS:验证请求类型(检查JSON或HTML)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查客户端请求的类型是JSON还是HTML,因为我希望我的路由满足人机和机器的需求。

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.

我已阅读Express 3文档:

I have read the Express 3 documentation at:


http://expressjs.com/api.html

有两种方法 req.accepts() req.is(),使用如下:

And there are two methods req.accepts() and req.is(), used like this:

req.accepts('json') 

req.accepts('html') 

由于这些都不行,所以我尝试使用:

Since these are not working as they should, I tried using:

var requestType = req.get('content-type');

var requestType = req.get('Content-Type');

requestType 总是未定义 ...

使用此线程的建议:


Express.js检查请求类型。 is()不工作

也不起作用。我究竟做错了什么?

does not work either. what am I doing wrong?

编辑1 :我检查过正确的客户端HTML协商。这是我的两个不同的请求标头(从调试器检查器获取):

Edit 1: I have checked for correct client HTML negotiation. Here are my two different request headers (taken from the debugger inspector):


HTML:接受:text / html ,application / xhtml + xml,application / xml; q = 0.9,* / *; q = 0.8

JSON:接受:application / json,text / javascript,* / *; q = 0.01






(感谢Bret):


Solution (thanks to Bret):

原来我指定了接受标题错误,而 * / *

Turns out I was specifying the Accept headers wrong, and the */* was the issue. Here is the code that works!

//server (now works)
var acceptsHTML = req.accepts('html');
var acceptsJSON = req.accepts('json');

if(acceptsHTML)  //will be null if the client does not accept html
{}

我正在使用JSTREE,一个使用jQuery Ajax调用的jQuery插件。传递给Ajax调用的参数在ajax字段中,我已经用一个完整的headers对象替换了accept参数。现在它的工作原理,并且应该解决问题,当你使用纯粹的jQuery,如果它应该发生。

I am using JSTREE, a jQuery plugin that uses jQuery Ajax calls underneath). The parameters passed to the Ajax call are in the "ajax" field, and I have replaced the "accepts" parameter with a complete "headers" object. Now it works, and should solve the problem when you are using plain jQuery if it should ever occur.

//client 

.jstree({
            // List of active plugins
            "plugins" : [
                "themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu"
            ],

            "json_data" : {
                "ajax" : {
                    // the URL to fetch the data
                    "url" : function(n) {
                        var url = n.attr ? IDMapper.convertIdToPath(n.attr("id")) : "<%= locals.request.protocol + "://" + locals.request.get('host') + locals.request.url %>";
                        return url;
                    },
                    headers : {
                        Accept : "application/json; charset=utf-8",
                        "Content-Type": "application/json; charset=utf-8"
                    }
                }
            }
        })


推荐答案

var requestType = req.get('Content-Type'); 绝对有效,如果一个内容类型实际上在请求中指定(我只是re - 一分钟前验证)。如果没有定义content-type,那么它将是未定义的。请记住,通常只有POST和PUT请求将指定内容类型。其他请求(如GET)通常会指定接受类型的列表,但这显然不一样。

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.

编辑:

好的,我现在更了解你的问题。你正在谈论接受:标题,而不是内容类型。

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

发生了什么:注意 * / *; q = 0.8 在列表接受类型的末尾?这基本上说我会接受任何东西。因此,由于技术上它是一个被接受的内容, req.accepts('json')总是返回json

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.

我想你想要看是否明确列出了 application / json ,如果是,在json中回应,否则在html中回复。这可以通过几种方式完成:

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
}

或使用简单的正则表达式:如果(/ application \ / json; /。test(req.get('accept'))){


or using a simple regular expression:

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

这篇关于NodeJS:验证请求类型(检查JSON或HTML)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆