Search code examples
javascriptangularjsnode.jscorsplunker

How to connect plunker to a local Node.js server?


I want to connect my plunk to a node server running on my local machine. I want to achieve this in order to obtain some data from a database. At the moment I have created some sample data in the app.js file on my plunk.

Is there any way to do this? If not with plunker, is there any alternative where I can run Node.js apps online?


Solution

  • Regarding your question about an alternative for hosting Node.js apps you could have a look at Cloud9

    Update: It is possible to connect to a local machine but you have to take CORS into consideration. I made a quick sample to show you that it is possible. Following is a simple Node.js application which responds with "Huhu!" when sending a GET to http://localhost:3000/ping

    var express = require('express');
    var cors = require('express-cors')
    var app = express();
    
    app.use(cors({
        allowedOrigins: [
            'run.plnkr.co'
        ]
    }));
    
    app.get('/ping', function(req, res) {
        res.send('Huhu!');
    });
    
    app.listen(3000, function () {
      console.log('Example app listening on port 3000!');
    });
    

    In addition, here is a simple Plunker for connecting to it, whereby the 'important' part is

    $scope.pingLocalNodeServer = function() {
      $http.get('http://localhost:3000/ping')
           .then(function(response) {
              $scope.echo = response.data;
            }, function(error) {
              $scope.err = error;
            });
      };
    

    Hope that helps you