Steve_bing
Steve_bing

Reputation: 45

Node.js(express) .end() with JSONP

I have a function like

User.prototype._send = function(type, code, message, callback) {
    if(!message && typeof code != 'number') {
        callback = message;
        message = code;
        code = 200;
    }

    if(typeof message != 'string')
        message = JSON.stringify(message);

    if(type == 'connection' && this.connection) {
        this.connection.writeHead(code || 200, {
            'Content-Type': 'application/json',
            'Content-Length': message.length
        });
        this.connection.end(message);
    } else {
        if(!this.listeners.length)
            return this.message_queue.push(arguments);

        var cx = this.listeners.slice(), conn;
        this.listeners = [];
        while(conn = cx.shift()) {
            conn.writeHead(code || 200, {
                'Content-Type': 'application/json',
                'Content-Length': message.length
            });
            conn.end(message);
        }
        if(callback) callback();
    }
};

It returns JSON to the client now. But I want it to return JSONP. I did a lot of research and tried to replace .end with .jsonp but it does not work.

Upvotes: 2

Views: 1525

Answers (2)

user2840784
user2840784

Reputation: 81

JSONP("JSON with padding") is a communication technique and is not an another object notation. See http://en.wikipedia.org/wiki/JSONP for more details.

Basically your application need to accept the query parameter jsonp and wrap the json message with that parameter or callback as shown below

var jsonpCallback = req.query.jsonp; //Assuming you are using express

message = JSON.stringify(message);

message = jsonpCallback + "(" + message + ");"

Upvotes: 3

aaronfay
aaronfay

Reputation: 1692

As user2840784 points out, you need the callback for this to work. To elaborate on their answer, the client library will need to specify a 'client side callback' when making the request for example:

http://my-service.com/get-data.json?callback=callThisFunction

If you're using jQuery on the client side, jQuery will provide the callback name for you when you make the $.ajax request, so your request will look like:

http://my-service.com/get-data.json?callback=jQuery123456789

Behind the scenes, jQuery secretly creates a function with the name jQuery123456789 (or something) to handle your data when it's loadded.

What you have to do is make sure you wrap your JSON output with the callback function name, so if your response JSON would look like this:

{"a":1, "b":2}

... then you need to wrap it so it looks like this:

jQuery123456789('{"a":1, "b":2}')

Again, as user2840784 pointed out, you can get the name of the callback from req.query.jsonp.

Hth,
Aaron

Upvotes: 1

Related Questions