Node.js end to end example with AJAX

In this article am going to explain how to get started with Node.js scripts and writing your own web services in Node.js.

Before starting with writing the server logic we need to learn how to install and run Node.js programs, If you’re not familiar with it, go through one of my previous article How to run hello world program in node.js.  

Now let me describe the example which we will be following, Here let’s just create an input field to enter your name in the front end with a button to call the service with a GET request.
In the back end we will be adding some text to your name and return it to the front end which will be displayed.

Front end

and the function definition for callServer would be

Back end

Now lets code the back-end part in a new .js file, I suggest using express.js module for writing services which is used to write REST APIs by routing technology.

To install express in your project, open command prompt in administrator mode and traverse to the folder where your node.js project is, and execute the command “npm install express”. Node package manager will take care of installing express in your project.

Once it is installed we can use express module in our file by using the “require” method provided by node.

app.use method is used to resolve the CORS error thrown by browsers when you’re accessing the server which is running in different port or at different URI. This is not required in case of production or the view part is inside your node project.

app.get is the get method which acts at the location “http://localhost:8080/home”. Let’s run the node file by executing ” node yourFileName.js” like how you executed the helloworld.js program file. Now we are ready with our server running in our local machine at port 8080.

Open the html file in the browser and test the connectivity by typing your name inside the input box and clicking on the button..



Tagged as: , , ,