سؤال

I'm attempting to create a simple web service using node.js, express, monk, and mongodb which returns results from mongodb based on the params in the URL. I want to add jsonp support to the calls. The service will be called as such:

localhost:3000/database/collection/get?param1=Steve&param2=Frank&callback=foo

app.js

var mongo_address = 'localhost:27017/database';
var db = monk(mongo_address);
app.get('/:coll/get', routes.handle(db);

routes/index.js

exports.handle = function(db) {
    return function(req, res) {

        // Send request
        db.get(req.params.coll).find(req.query, {fields:{_id:0}}, function(e,docs) {
            if (e) throw e;         
            res.jsonp(docs)
        });
    };
}

When I use the built in JSONP support with res.jsonp, it sends the callback param to mongo and returns an empty list. I've tried stripping out the callback param during the query and then manually adding it back to the results without much luck. I feel like I'm missing something simple. Any help would be appreciated.

هل كانت مفيدة؟

المحلول

After some messing around with JS, I found a workable solution with minimal additional code. AFter stripping the callback from the query and storing the function value, I had to explicitly build the return string for JSONP requests.

exports.handle = function(db) {
    return function(req, res) {
        //Determine if URL implements JSONP
        var foundCallback = req.query.callback;
        var callbackVar;
        //If asking for JSONP, determine the callback function name and delete it from the map
        if (foundCallback){
            callbackVar = req.query.callback;
            delete req.query.callback
        }

        // Send request
        db.get(req.params.coll).find(req.query, {fields:{_id:0}}, function(e,docs) {
            if (e) throw e;

            //If callback, send function name and query results back, else use express JSON built in
            if (foundCallback)
                res.send('typeof ' + callbackVar + ' === \'function\' && ' + callbackVar + '(' + JSON.stringify(docs) + ');');
            else
                res.json(docs);
        });
    };
}

نصائح أخرى

Try

app.set("jsonp callback", true);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top