Jsonp route for API


#1

Does anyone know of an easy way to serve up a jsonp endpoint? In Express it’s a one-liner: http://expressjs.com/api.html#res.jsonp
But I can’t seem to find any mentions in jsonp in the relevant packages (Restivus, JsonRoutes, etc.).


#2

Give a try for JsonRoutes


#3

I’ve looked into JsonRoutes already, but I don’t see how it can be configured to return JSONP.
How would you do that?


#4

the name of your callback should be placed in query string. In common case it looks like /api/get/result?callback=foo. So you can simply respond as

response.write(query.callback + '(' + JSON.stringify(yourJSONDataHere) + ')')

Don’t forget about headers)


#5

Thanks for the suggestion. I tried that, but JsonRoutes hardcodes the content-type header: https://github.com/stubailo/meteor-rest/blob/master/packages/json-routes/json-routes.js#L64

So it doesn’t respond with useable jsonp.


#6

No, you can use res (response) directly instead of sendResult. Like:

JsonRoutes.add 'GET', 'api/get/result', (req, res, next) ->
    res.setHeader(...)
    res.write(req.query.callback + '(' + JSON.stringify(...) + ')')
    res.end()