How to create RestFul api with express and node.js?

advertisements

I am very new to node and express i read some documentation but i did not get any solid understanding how to create rest api with node, So with below basic code i just want to create get api with express and return response to angularjs factory method.I would like to get help and better understanding for the following .

1- How to return response with GET api ?

2- If we have json object how can i pass that data using GET api ?

app.js

var express = require('express');
var path = require('path');

var app = express();
app.use(express.static('./'));

var server = app.listen(3000, function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http',host,port);
});

app.get('/test', function(req, res) {
  res.type('text/plain'); // set content-type
  res.send('i am a beautiful butterfly'); // send text response
});

workerController.js

$scope.getTestData = function(){
        alert('got function working');
        workerFactory.getData().then(function(response){
            var dataResponse = response.data;
            console.log(dataResponse);
        })
    }

workerFactory.js

angular.module('myApp').factory('workerFactory', function ($http) {
    'use strict';
    return {
        getData: function(){
            return $http.get('/test');
        }
    }
});


For the second part, how to pass a JSON object back. You can change your API code to something like:

app.get('/test', function(req, res) {
  res.json({message: 'i am a beautiful butterfly'}); // send a JSON response
});

I'm just working on the first part of the question