Node JS Express for Beginners

Node JS Express for Beginners

July 14, 2023

Read Time 4 minutes

Node.js is a server-side JavaScript environment that allows developers to run JavaScript code on the server rather than just in the browser. Here will explain the simplest way to set up a counter incrementer server.

Setup

To implement a Node.js Express server and maintain a counter, you'll need to set up a simple API endpoint from the front-end app to increment/decrement and update the counter accordingly.

Create a new directory for your project and initialize a Node.js project using npm or yarn.

      
        npm init
      
    

Install Express to create the server.

      
        npm install express
      
    

Create Server

In the root of the project, create a file that will contain the express server code. Call it server.js or index.js

In the server.js lets import express, and use it. Lets also use bodyParser to parse JSON data from the request body.

server.js
      
        const express = require('express');
const app = express();
const bodyParser = require('body-parser'); 

app.use(bodyParser.json());
      
    

Now lets try to start the server. Add in this code and run the command node server.js in the terminal

server.js
      
        const port = 3000; // You can change this to any desired port number
app.listen(port, () => {
  console.log(`Server is running on ${port}`);
});
      
    

You will see the console log if the server is running successfully.

Next we will need to initialize a counter variable.

server.js
      
        let counter = 0;
      
    

Create end point to update the counter.

server.js
      
        app.get('/increment', (req, res) => {
  counter++
  res.json({ vueCounter })
})
      
    

Add another end point to subtract from the counter if you'd like.

In your front end app, you can make requests to this end point to update the counter. Here is a simple Vue template that will work for this. We will use axios to make requests.

vue
      
        <script setup lang='ts'
      import { ref } from 'vue'
      import axios from 'axios'

      const counter = ref(0);
      
      function increment (){
        axios
      .get('https //localhost:3000/increment')
      .then((response: any) => {
        counter.value = response.data.counter
      }
    </script>
    <template>
        <div class='counter-app'>
            <button @click='increment'>add</button>
            <span>{{ counter }}</span>
        </div>    
    </template>    
      
      
    

Test it out and see if it works. Make sure the server is running and are making the request to the correct url. That's it!

Deploy

There are several user-friendly hosting platforms that make it easy to deploy and manage web applications, including Node.js apps. Here are some simple and popular hosting

Make sure to switch to the correct url in the front-end given from the hosting platform after deploying.

Photos from unsplash