我想检查我的客户端请求的类型是JSON还是HTML,因为我希望我的路由满足人力和机器需求.
我在以下网址阅读了Express 3文档:
这里面有两个方法req.accepts()和req.is(),像这样使用:
req.accepts('json')
Run Code Online (Sandbox Code Playgroud)
要么
req.accepts('html')
Run Code Online (Sandbox Code Playgroud)
由于这些不能正常工作,我尝试使用:
var requestType = req.get('content-type');
Run Code Online (Sandbox Code Playgroud)
要么
var requestType = req.get('Content-Type');
Run Code Online (Sandbox Code Playgroud)
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
解决方案(感谢布雷特):
事实证明我正在指定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
{}
Run Code Online (Sandbox Code Playgroud)
我正在使用JSTREE,一个在下面使用jQuery Ajax调用的jQuery插件.传递给Ajax调用的参数位于"ajax"字段中,我已将"accepted"参数替换为完整的"headers"对象.现在它可以工作,并且应该在使用普通jQuery时解决问题,如果它应该发生的话.
//client
.jstree({
// List of active plugins
"plugins" : [ …Run Code Online (Sandbox Code Playgroud)