【问题标题】:With expressJS, does res and req pass through to functions?使用 expressJS,res 和 req 是否传递给函数?
【发布时间】:2011-09-13 04:23:21
【问题描述】:

我正在使用CoffeeScript,请注意:

searchResults = (err, data)->
  res.write 'hello'
  console.log data
  console.log 'here'
  return


exports.search = (req, res) ->
  res.writeHead 200, {'Content-Type': 'application/json'}
  location = req.param 'location'
  item = req.param 'item'

  geoC = googlemaps.geocode 'someaddress', (err, data) ->
      latLng = JSON.stringify data.results[0].geometry.location

      myModule.search latLng, item, searchResults

      return
  return

searchResults 函数不知道res,那我如何将数据返回给浏览器呢?

【问题讨论】:

    标签: node.js coffeescript express


    【解决方案1】:

    这是一个很常见的场景。一种选择是在exports.search 内部定义searchResults,但随后exports.search 可能会变得笨拙。

    searchResults 定义为在 res 不是参数时使用 res 是没有意义的。但是您可能不愿意使用带有多个参数的函数,当您有多个需要访问相同状态的回调时,这可能会导致重复代码。一个不错的选择是使用单个散列来存储该状态。在这种情况下,您的代码可能类似于

    searchResults = (err, data, {res}) ->
      ...
    
    exports.search = (req, res) ->
      res.writeHead 200, {'Content-Type': 'application/json'}
      location = req.param 'location'
      item = req.param 'item'
      state = {req, res, location, item}
    
      geoC = googlemaps.geocode 'someaddress', (err, data) ->
          state.latLng = JSON.stringify data.results[0].geometry.location
          myModule.search state, searchResults
          return
      return
    

    注意myModule.search 现在只接受state 哈希和回调;然后它将 state 哈希作为第三个参数传递给该回调 (searchResults),它使用解构参数语法将 res 从哈希中提取出来。

    【讨论】:

      【解决方案2】:

      标准绑定就可以了。

      myModule.search latLng, item, searchResults.bind(null, res)
      
      ...
      
      searchResults = (res, err, data)->
        res.write 'hello'
        console.log data
        console.log 'here'
        return
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 2021-02-04
        • 2011-06-09
        • 1970-01-01
        相关资源
        最近更新 更多