• Blogs (9)
    • đŸ“± 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • Node.js: CORS/JSONP RESTful-API service

    Blogs20142014-04-22


    Node.js: Node.js: CORS/JSONP RESTful-API service

    I setup a testing server ‘dummy_domain’ as a CORS-based RESTful-API server to provide general data.

    • Setup a node.js expressjs server
    • Setup a MongoDB daemon with the server to provide/remain data
    • Configure th server to support CORS/JSONP, RESTful-API service
    • Test to allow access from other domains (anywhere to call JSONP-Restful APIs)

    The following are steps: In expressjs’s ‘app.js’ file, adding the following at the bottom:

    server.listen(8999);
    
    app.all('*', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });
    
    app.get('/api/cors', function (req, res, next) {
        res.sendfile(__dirname + '/index.html');
    });
    app.post('/api/cors', function (req, res, next) {
        console.log(req.body);
        //res.json({ user: req.body });
        res.jsonp({ user: req.body });
    });
    app.get('/api/cors/:id?', function(req, res, next) {
        if(req.params.id) {
            res.send(200, {id: req.params.id });
        }
        else {
            res.send(500, 'No params Id');
        }
    });

    The above is the server-side settings, very simple. The following are client’s side to call ‘dummy_domain:8999’ JSONP RESTful-API service:

    //1. in other node.js server (server-call-server):
    app.get('http://dummy_domain:8999/api/cors', function(req, res) {
      console.log(req, res);
    });
    app.get('http://dummy_domain:8999/api/cors/123', function(req, res) {
      console.log(req.params, req.query);
      res.send(req.params.id);
    
    });
    
    //2. from jQuery:
    $.ajax({
        url: 'http://dummy_domain:8999/api/cors',
        data: {id: 123},
        type: 'GET',
        dataType: 'jsonp',
        crossDomain: true,
        success: function(data) {
        	console.log(data);
        }
    });
    $.ajax({
        url: 'http://dummy_domain:8999/api/cors',
        type: 'POST',
        dataType: 'jsonp',
        crossDomain: true,
        success: function(data) {
        	console.log(data);
        }
    });
    // or call from Backbone's collection/model, or from Angularjs $resource.

    It works fine, can be put to heroku to provide cloud service. A very helpful website is enable cross-origin resource sharing for reference.