Introduction
In a previous post https://www.rsprog.de/aspnet-webapi2-angularjs/ I used ASP.NET WebAPI 2 for creating a small sample web application. Here, I will use Node.js as the server backend.
Node.js can be an alternative way for the server backend. It is especially useful if we want to have the option of providing support for Linux too.
In this article, we concentrate on Windows and describe how we install Node.js and create the server.
Installation of Node.js
♦ https://nodejs.org/de/download/
♦ We assume that node.exe was added to the path, so we can open a commandline. First check:
node -v
(displays the version)
♦ Create a new directory for the source and enter:
npm init
♦ And answer:
package name: angulartest
version: (1.0.0)
description: Node.js AngularJS Test
entry point: app.js
test command:
git repository:
keywords:
author: Your Name
license: (ISC)
A new file package.json has been created in the current directory. We can edit if we want to change anything.
♦ Then add npm modules:
npm install express –save
npm install body-parser –save
♦ Create app.js
var express = require('express'); var bodyParser = require('body-parser'); const SUFFIX = '/personapiv1/'; var app = express(); // Initialize Body Parser for JSON decoding app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Disable cacheing of client requests app.use(function (req, res, next) { res.header("Cache-Control", "no-cache, no-store, must-revalidate"); res.header("Pragma", "no-cache"); res.header("Expires",0); next(); }); var persons = []; persons.push({ Name: "Alice", Age: 9 }); persons.push({ Name: "Bob", Age: 26 }); persons.push({ Name: "Charly", Age: 17 }); persons.push({ Name: "David", Age: 59 }); persons.push({ Name: "Elizabeth", Age: 13 }); persons.push({ Name: "Mary", Age: 67 }); persons.push({ Name: "Edward", Age: 40 }); // Routings app.get(SUFFIX + 'persons', function (req, res) { res.json(persons); }); // serving the static files app.use('/', express.static(__dirname + '/Content')); app.listen(80);
Now the server can be started with
node app.js