使用expressJS,res和req是否传递给函数?
我正在使用 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
,那么我如何将数据返回到浏览器?
I'm using CoffeeScript
, just a heads up:
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
The searchResults
function doesn't know about res
, so how can I return data to the browser?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个很常见的场景。一种选择是在
exports.search
内部定义searchResults
,但是exports.search
可能会变得笨拙。当
res
不是参数时,以使用res
的方式定义searchResults
是没有意义的。但是您可能不愿意使用带有多个参数的函数,当您有多个需要访问相同状态的回调时,这可能会导致重复的代码。一个好的选择是使用单个哈希来存储该状态。在这种情况下,您的代码可能类似于注意
myModule.search
现在仅采用state
哈希值和回调;然后,它将state
哈希作为第三个参数传递给该回调 (searchResults
),该回调使用解构参数语法从哈希中提取res
。It's a pretty common scenario. One option is to define
searchResults
inside ofexports.search
, but thenexports.search
might get unwieldy.It doesn't make sense for
searchResults
to be defined in such a way that it usesres
whenres
isn't an argument. But you may be reluctant to have functions with several arguments, which can lead to repetitive code when you have several callbacks that need to access the same state. One good option is to use a single hash to store that state. In this case, your code might look something likeNotice that
myModule.search
now only takes thestate
hash and a callback; it then passes thestate
hash as the third argument to that callback (searchResults
), which pullsres
out of the hash using the destructuring argument syntax.标准绑定就可以了。
A standard bind will do.