Share via


Create and Host your Node.js API in Azure

Node.js is an Open source, Cross-platform, and runtime environment for executing JavaScript code outside the browser. We can build Web apps and APIS using Node.js.
This is
Super-fast and highly scalable e.g. PayPal, Uber, Netflix
Builds twice as fast with fewer people
33% fewer lines of code
40 % fewer files
2x request/sec
35% faster response.

So first let's create an API using Node.js.
Before we proceed, we must ensure we have the following installed in your computer : Node.js

To check if you have Node.js installed, run this command in your terminal:node-v
To confirm that you have npm installed you can run this command in your terminal: npm-v

After the confirmation, let's create a new folder and go into it by following commands,

            mkddir nodejsAPI

            cd nodejsAPI

 

Initiate a new NPM project with this command npm init and provide all the details requested for.

So let's add ExpressJS framework to create our API.

To use ExpressJS in our application, we need to execute following two commands.

            npm install express --save

            npm install body-parser --save

 

Then we have to create a new file named: app.js

And let's add the content as following,

//-------------------

var express = require("express");

var bodyParser = require("body-parser");

var routes = require("./routes/routes.js");

var app = express();

var port=process.env.PORT || 3000;

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

routes(app);

app.listen(port);

console.log('Server Listening at port'+port);

//--------------------------

As per the code this will get expressjs framework and body parser to get the http request body. And this will run on localhost with port 3000.

Now let's create routes.js which is our code going to write. So for that create new folder and name it as "routes" , then create the routes.js inside the routes folder.

Then add the content of the routes.js file as follows.

//-------------------------

var appRouter = function (app) {

     app.get("/", function (req, res) {

          res.status(200).send({ message: 'Welcome to our restful API' });

     });

     app.get("/getItems/:num", function (req, res) {

          var num =req.params.num;

          var data = {

               'item1': 'https://public-domain-photos.com/free-stock-photos-1/flowers/cactus-76.jpg',

               'item2': 'https://public-domain-photos.com/free-stock-photos-1/flowers/cactus-77.jpg',

               'item3': 'https://public-domain-photos.com/free-stock-photos-1/flowers/cactus-78.jpg'

          }     

          res.status(200).send(data);

     });

     app.get("/getText/:txt", function (req, res) {

          var text =req.params.txt;

          var data = {

               'text': text

          }

          res.status(200).send(data);

     });

}

module.exports = appRouter;

//-------------------------

So as per the router.js, There are three APIs.

  • Index
  • getItems -- with parameter number
  • getText -- with parameter text

So now you can navigate to the folder by cmd and type "node app.js"

So your node API is now up in your local machine.

 

 

Let's change your settings to publish your application to Azure.

First change your package.json  as follows


{

    "name": "demonodeproject",

    "version": "1.0.0",

    "description": "writing first node app",

    "main": "app.js",

    "dependencies": {

          "express": "^4.14.0"

    },

    "scripts": {

       "start": "node app.js"

    }

}

-----------------

Here the scripts section will run after the app published to azure.

Then let's add web.config file.

------------------

<configuration>

    <system.webServer>

       <handlers>

          <add name="iisnode" path="app.js" verb="*" modules="iisnode" />

       </handlers>

          <rewrite>

             <rules>

                <rule name="myapp">

                   <match url="/*" />

                      <action type="Rewrite" url="app.js" />

                </rule>

                <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">

                   <match url="^app.js\/debug[\/]?" />

                </rule>

              </rules>

       </rewrite>

       <defaultDocument enabled="true">

          <files>

             <add value="app.js" />

          </files>

       </defaultDocument>

    </system.webServer>

</configuration>

-------------------

So now your folder structure needs to be like this. :)

Let's create Web App Service in Azure.

So your app service is up and running.

Now what you have to do is, just zip all the content in your nodejs folder.

Then navigate https://<your app name>.scm.azurewebsites.net/ZipDeploy 

and upload your zip file.

(https://testingnodeapp.scm.azurewebsites.net/ZipDeploy)

And also you can use https://testingnodeapp.scm.azurewebsites.net to manage your web app in Azure.

After successful upload of your zip file, Kudu service will extract and publish your files to the Azure web app.

Now you can use you Node.js API. as https://<your app name>.azurewebsites.net

(https://testingnodeapp.azurewebsites.net/)

So as per the previous local URLs, you can use this also in the same way.

(https://testingnodeapp.azurewebsites.net/getText/Hello user)

(https://testingnodeapp.azurewebsites.net/getItems/2)

 

I'm sharing my github repository of the API I've created.

https://github.com/kavindasas/Node-JS-API-with-Azure

Hope you understood :)

References: /en-us/javascript/azure/?view=azure-node-latest