Serve JSONP to script-based clients
A legacy browser client requests cross-origin data through a script callback.
Express.js · Module
res.jsonp() sends a JSON response with JSONP callback support. It accepts a JSON-compatible body; set status separately with res.status().jsonp(body).
Call res.jsonp with any JSON-compatible value to send it as a response with JSONP support. Express uses the callback query parameter and wraps the serialized value with that callback; configure the default callback parameter name through the application setting. Set HTTP status separately with res.status().
res.jsonp(body)
res.status(status).jsonp(body)| Name | Type | Description |
|---|---|---|
body | any | undefined | The JSON-compatible value to serialize and send as the JSONP response; it may be omitted. |
status | Number | undefined | Deprecated positional HTTP status code; use res.status() instead. |
Response
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
res.jsonp({ user: 'tobi' });
});
app.listen(3000);Start the server and request /data?callback=handleData to receive the object wrapped for JSONP.
A legacy browser client requests cross-origin data through a script callback.
An endpoint must return an object wrapped in a named callback function.
A response needs a non-default HTTP status while retaining JSONP formatting.
res.jsonp(body) sends a JSON response while opting into JSONP callback support. The response is wrapped using the requested callback, such as callback({...}).
Follow-up: How should a non-success status be sent? Call res.status(code).jsonp(body), rather than using a deprecated positional status overload.
The body argument can be any JSON type, including null, objects, arrays, strings, numbers, or booleans. Express serializes that value and emits it with JSONP support.
Follow-up: What should replace res.jsonp(body, status)? Use res.status(status).jsonp(body).
The default JSONP callback name is callback. The application can override it with the jsonp callback name setting.
Follow-up: What related response setting can improve security when responses may be interpreted as HTML? json escape makes res.json and res.jsonp escape <, >, and & as Unicode sequences.
res.json()res.status()jsonp callback namejson escape