【发布时间】:2013-09-24 23:41:42
【问题描述】:
我想检查我的客户端请求的类型是 JSON 还是 HTML,因为我希望我的路由同时满足人类和机器的需求。
我已阅读 Express 3 文档:
还有req.accepts()和req.is()两种方法,使用方式如下:
req.accepts('json')
或
req.accepts('html')
由于这些不能正常工作,我尝试使用:
var requestType = req.get('content-type');
或
var requestType = req.get('Content-Type');
requestType 始终是undefined...
使用这个帖子的建议:
也不起作用。我做错了什么?
编辑 1:我检查了正确的客户端 HTML 协商。这是我的两个不同的请求标头(取自调试器检查器):
HTML:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8JSON:
Accept: application/json, text/javascript, */*; q=0.01
解决方案(感谢 Bret):
原来我指定的 Accept 标头错误,而 */* 是问题所在。这是有效的代码!
//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”字段中,我已将“accepts”参数替换为完整的“headers”对象。现在它可以工作了,并且当你使用纯 jQuery 时应该解决问题,如果它应该发生的话。
//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"
}
}
}
})
【问题讨论】: