如何在 coffeescript 中执行 HTTP GET 以从 REST API 获取 JSON

How to do a HTTP GET in coffeescript to get a JSON from a REST API

我正在寻找一种在 Coffeescript 中获取 REST API 并获得 json 的简单方法。我正在使用 request library。当我这样做时,什么也没有发生,没有错误。

request = require 'request'

resp = ""
request.get {uri:'https://api.service.co/search?query=paris', json : true}, (err, r, body) -> resp = body
console.log "BODY: " + resp

我做错了什么?您知道在 coffeescript 中从 REST api 获取 json 的更好方法吗?非常感谢!

我怀疑你的问题是 request.get 异步执行,所以当它到达 console.log 语句时,resp 总是 "".

试试这个:

request = require 'request'

resp = ""
request.get {uri:'https://api.service.co/search?query=paris', json : true}, (err, r, body) ->
  resp = body
  console.log "BODY: " + resp