I'm have a REST API service, written on Node.js + Express, which currently support responses in JSON format.
Now, I need to add support for JSONP responses too, so everyone may get it by adding alt=JSONP to the request string.
So, my question is, which is the best way to do so?
Possible, there is an pattern, or living example?
Thanks!
The officially supported method is as follows --
First, set your JSONP callback parameter name:
app.set('jsonp callback name', 'callback');
Then, change all instances of res.json
or res.send
to res.jsonp
.
For example, res.jsonp(500, { error: 'message' })
If the callback
parameter is supplied in a request, the response will be wrapped as JSONP using the supplied function name, but if it isn't, it'll just return JSON.
Afterwards, this returns JSONP: GET /myapi/v1/users?callback=responseCallback
This does not: GET /myapi/v1/users