How To Create Simple Node.js API In Visual Studio

In this article, we’ll learn how to create a simple Node.js API In Visual Studio.

What is Node.js?

Node.js is an open-source server environment that executes JavaScript server-side.

What is npm?

For the Node.js, npm is the default package manager. The package manager makes it easier to share and publish the source code of Node.js libraries and is designed to simplify installation, uninstallation, and updating of Node.js libraries.

What is express?

Express is a web application framework for Node.js, used as a server framework for Node.js to build web applications. Express allows you to use choose different front-end frameworks to create a User Interface (UI).

Prerequisites

  • Visual Studio 2019

If you haven’t already installed Visual Studio 2019, go to the link given below to install it for free.

Download Visual Studio 2019

If you need to install the workload but already have Visual Studio, click on Continue without code.

Then go to Tools -> Get Tools and Features…, which opens the Visual Studio Installer. Choose the Node.js development workload, then click on the Modify button.

 

    • Node.js runtime

If you don’t have it installed, install the LTS version from the link given below.

Download Node.js

 

    • Postman

If you haven’t already installed Postman, go to the link given below to install it for free.

Download Postman

Create a new Node.js API project

In this tutorial, we are creating a simple project containing code for a Node.js API and express app.

  1. Open Visual Studio
  2. Create a new project

Choose Basic Azure Node.js Express 4 Application (JavaScript).

Now, set the Project name and Location, and then click on the Create button.

Node.js project is created.


Now we have to delete all views files. Because we are creating API so we don’t need any views file in this project.

Open the index.js file from the routes folder and add the code in it. (Status Success)

'use strict';
var express = require('express');
var router = express.Router();

/* Return Status OK. */
router.get('/', function (req, res) {
    res.status(200).send();
});

module.exports = router;

Output:

Open the index.js file from the routes folder and add the code in it. (Status Error)

'use strict';
var express = require('express');
var router = express.Router();

/* Return Status Bad Request. */
router.get('/', function (req, res) {
    res.status(400).send();
});

module.exports = router;

Output:

 

Also, check How To Create Node.js App In Visual Studio

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories