In this tutorial we will learn how to create and deploy the sample Node.js application on SAP Cloud Foundry. Follow the below mentioned steps to create your first Node.js module in 10 seconds.
Create the MTA project, refer below mentioned blog for details.
SAP Cloud Foundry MTA project
- Now we will create the Node.js module. Right click on the MTA project folder and choose "New" and select "Node.js Module".
- Enter the Module Name and press Next.
- It will specify the version as "1.0.0" and Main JS file as "server.js". Enter the description and press Next and finish.
We can see that Node Module folder is created within the MTA project. Open the project.json file and provide the express dependency with version as "^4.0.0". We will be using express framework in node application that provides a robust set of features for web and mobile applications.
"dependencies": {
"express": "^4.0.0"
},
Within the Node Module folder we have server.js file which is the starting point of the application. In this file we will do the configuration so that application will start listening to the server ports and give the response back to the client requests.
"use strict";
const express = require('express');
const app = express();
var port = process.env.PORT || 3000;
app.get('/', function (req, res) {
res.send("Hello World\n");
});
app.listen(port);
console.log("Server listening on port %d", port);
We have successfully created our first Node.js application. Now to run the application, right click on the Node Module folder, choose "Run" and click on the "Run as Node.js application". It will build task for npm install and run the application.
Nodejs build task "npm install" started
Service provisioning started
Service provisioning finished
Nodejs build task "npm install" finished successfully
Application is starting
Application is running
> Node_Tutorial@1.0.0 start /home/vcap/app
> node server.js
Server listening on port 3000
It will also generate the URL so that we can test the application in the browser or use it as REST API in any application.
We might face error while running the Node.js module in case the cloud foundry setting are not configured for the account endpoints.
Request failed: error URI: /di/runner/run?project=/first_mta_project/Node_Tutorial
Unable to run module.
Running module /first_mta_project/Node_Tutorial failed. See console logs for more details. Request failed: error URI: /di/runner/run?project=/first_mta_project/Node_Tutorial
Follow below mentioned steps resolve the error.
- Click on the settings icon in the left hand side panel and select "Cloud Foundry" from Workspace Preferences.
- Go to trial account home page in cockpit to check the API endpoints and the select the corresponding API from the dropdown.
- It will ask for Email Id and Password and on successful authentication, it will populate the Organization and and Space.
- Click Save and re run the Node.js application.