【问题标题】:How to determine the right Accept Content-Type with ExpressJS如何使用 ExpressJS 确定正确的 Accept Content-Type
【发布时间】:2016-07-16 16:05:39
【问题描述】:

我无法区分 ajax 调用和 ExpressJS 中的其他调用。

据我了解,我可以使用request.accepts('json')来识别一个json请求吗?

问题是 - 显然,每个调用都接受一切!

app.get( '*', function(request, response, next ) {
    console.log('request accepts:')

    if( request.accepts( 'json' ) ){
        console.log( '--> accepts json' )
    }
    if( request.accepts( 'html' ) ){
        console.log( '--> accepts html' )
    }
    if( request.accepts( 'blah' ) ){
        console.log( '--> accepts blah' ) // this does not show up
    }
    if( request.accepts( 'application/json' ) ){
        console.log( '--> accepts json2' )
    }

    next()
} )

如果我只是访问该页面,它接受 json 和 html。

如果我尝试使用$.getJSON( ... url ... ),它也接受 json 和 html。

Headers:

Browser: "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Ajax: "Accept application/json, text/javascript, */*; q=0.01"

我不是接受标头方面的专家,但似乎*/* 部分可能是问题所在。

如何在 ExpressJS 中确定正确的(或者可能是第一个)接受类型? 或者:如何区分 JSON 请求和正常的页面访问?

【问题讨论】:

  • 很好奇为什么你首先需要这样做。如果您需要从相同的 url 提供不同的数据类型,大多数 API 使用查询参数,如 /path/to/server?format=json
  • @charlietfl 这样做的主要原因是因为我想在基于 json 的调用期间禁用一些与路径无关的中间件(在每种情况下都会调用)。由于路径路由似乎是在之后发生的,因此我无法为其设置标志(因为那时为时已晚)。我可以看到 2 个选项:要么制作一个模拟路由的中间件并检查是否调用了特定路径(嗯!),要么只是检查接受的类型。
  • 假设您拥有仅服务于 json 的 REST API,您不能只检查路由是否包含该 api 的主路径,例如 "/api/"。总的来说,这似乎是一个奇怪的问题
  • 还可以使用$.ajaxSetupbeforeSend回调中根据dataType设置自定义标头

标签: javascript jquery express http-headers http-accept-header


【解决方案1】:

浏览器发出的几乎所有 GET 请求都以*/* 结束,这意味着它几乎可以接受所有内容。为了做出决定,您可以检查req.accepted 数组。它看起来像这样:

[ { value: 'application/json',
    quality: 1,
    type: 'application',
    subtype: 'json' },
{ value: 'text/html',
     quality: 0.5,
     type: 'text',
     subtype: 'html' } ]

因此,如果存在 JSON,则为特殊请求,否则为简单请求

【讨论】:

    【解决方案2】:

    我找到了一个似乎可行的解决方案,方法是使用accepts() 的数组:

    if( request.accepts( [ 'json', 'html' ] ) == 'json' ) {
        // do something
    } else {
        // do something else
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2010-12-17
      • 2019-02-28
      • 2011-05-03
      • 2020-02-18
      • 2011-03-26
      • 2022-11-23
      相关资源
      最近更新 更多