Build a Weather App with Node and Express

Build a Weather App with Node and Express

Build a complete weather application using node and express. You will learn how to setup and static public directory through express.js. You will also learn how to render handlebar file using node and express. Following best structure and coding standards and learn to build full fledge rest apis using node and express.

Build a complete weather application using node and express. You will learn how to setup and static public directory through express.js. You will also learn how to render handlebar file using node and express.
Following best structure and coding standards and learn to build full fledge rest apis using node and express.

Node.js Express FrameWork Tutorial - Learn Express Framework

Node.js Express FrameWork Tutorial - Learn Express Framework

In this tutorial, we will study the Express framework. This framework is built in such a way that it acts as a minimal and flexible Node.js web application framework, providing a robust set of features for building single and multipage, and hybrid web application.

Originally published at https://www.guru99.com

In Node.js Express FrameWork tutorial, you will learn:

  • What is Express.js?
  • Installing and using Express
  • What are Routes?
  • Sample Web server using express.js
What is Express.js?

Express.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications.

It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack.

The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components;

1) MongoDB - The standard NoSQL database

2) Express.js - The default web applications framework

3) Angular.js - The JavaScript MVC framework used for web applications

4) Node.js - Framework used for scalable server-side and networking applications.

The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests.

Installing and using Express

Express gets installed via the Node Package Manager. This can be done by executing the following line in the command line

npm install express

The above command requests the Node package manager to download the required express modules and install them accordingly.

Let's use our newly installed Express framework and create a simple "Hello World" application.

Our application is going to create a simple server module which will listen on port number 3000. In our example, if a request is made through the browser on this port number, then server application will send a 'Hello' World' response to the client. 

var express=require('express');
var app=express();
app.get('/',function(req,res)
{
res.send('Hello World!');
});
var server=app.listen(3000,function() {});

Code Explanation:

  1. In our first line of code, we are using the require function to include the "express module."
  2. Before we can start using the express module, we need to make an object of it.
  3. Here we are creating a callback function. This function will be called whenever anybody browses to the root of our web application which is http://localhost:3000 . The callback function will be used to send the string 'Hello World' to the web page.
  4. In the callback function, we are sending the string "Hello World" back to the client. The 'res' parameter is used to send content back to the web page. This 'res' parameter is something that is provided by the 'request' module to enable one to send content back to the web page.
  5. We are then using the listen to function to make our server application listen to client requests on port no 3000. You can specify any available port over here.

If the command is executed successfully, the following Output will be shown when you run your code in the browser.

Output:

From the output,

  • You can clearly see that we if browse to the URL of localhost on port 3000, you will see the string 'Hello World' displayed on the page.
  • Because in our code we have mentioned specifically for the server to listen on port no 3000, we are able to view the output when browsing to this URL.
What are Routes?

Routing determine the way in which an application responds to a client request to a particular endpoint.

For example, a client can make a GET, POST, PUT or DELETE http request for various URL such as the ones shown below;

http://localhost:3000/Books
http://localhost:3000/Students

In the above example,

  • If a GET request is made for the first URL, then the response should ideally be a list of books.
  • If the GET request is made for the second URL, then the response should ideally be a list of Students.
  • So based on the URL which is accessed, a different functionality on the webserver will be invoked, and accordingly, the response will be sent to the client. This is the concept of routing.

Each route can have one or more handler functions, which are executed when the route is matched.

The general syntax for a route is shown below

app.METHOD(PATH, HANDLER)

Wherein,

1) app is an instance of the express module

2) METHOD is an HTTP request method (GET, POST, PUT or DELETE)

3) PATH is a path on the server.

4) HANDLER is the function executed when the route is matched.

Let's look at an example of how we can implement routes in the express. Our example will create 3 routes as

  1. A /Node route which will display the string "Tutorial on Node" if this route is accessed
  2. A /Angular route which will display the string "Tutorial on Angular" if this route is accessed
  3. A default route / which will display the string "Welcome to Guru99 Tutorials."

Our basic code will remain the same as previous examples. The below snippet is an add-on to showcase how routing is implemented. 

var express = require('express');
var app = express();
app.route('/Node',get(function(req,res)
{
    res.send("Tutorial on Node");
});
post(function(req,res)
{
    res.send("Tutorial on Angular");
});
put(function(req,res)
{
    res.send('Welcome to Guru99 Tutorials');
}));

Code Explanation:

  1. Here we are defining a route if the URL http://localhost:3000/Node is selected in the browser. To the route, we are attaching a callback function which will be called when we browse to the Node URL.
  2. The function has 2 parameters.
  • The main parameter we will be using is the 'res' parameter, which can be used to send information back to the client.
  • The 'req' parameter has information about the request being made. Sometimes additional parameters could be sent as part of the request being made, and hence the 'req' parameter can be used to find the additional parameters being sent.
  1. We are using the send function to send the string "Tutorial on Node" back to the client if the Node route is chosen.
  2. Here we are defining a route if the URL http://localhost:3000/Angular is selected in the browser. To the route, we are attaching a callback function which will be called when we browse to the Angular URL.
  3. We are using the send function to send the string "Tutorial on Angular" back to the client if the Angular route is chosen.
  4. This is the default route which is chosen when one browses to the route of the application – http://localhost:3000. When the default route is chosen, the message "Welcome to Guru99 Tutorials" will be sent to the client.

If the command is executed successfully, the following Output will be shown when you run your code in the browser.

Output:

From the output,

  • You can clearly see that we if browse to the URL of localhost on port 3000, you will see the string 'Welcome to Guru99 Tutorials' displayed on the page.
  • Because in our code, we have mentioned that our default URL would display this message.

From the output,

  • You can see that if the URL has been changed to /Node, the respective Node route would be chosen and the string "Tutorial On Node' is displayed.

From the output,

  • You can see that if the URL has been changed to /Angular, the respective Node route would be chosen and the string "Tutorial On Angular" is displayed.
Sample Web server using express.js

From our above example, we have seen how we can decide on what output to show based on routing. This sort of routing is what is used in most modern-day web applications. The other part of a web server is about using templates in Node js.

When creating quick on-the-fly Node applications, an easy and fast way is to use templates for the application. There are many frameworks available in the market for making templates. In our case, we will take the example of the jade framework for templating.

Jade gets installed via the Node Package manager. This can be done by executing the following line in the command line

npm install jade

The above command requests the Node package manager to download the required jade modules and install them accordingly.

NOTE: In the latest version of Node jade has been deprecated. Instead, use pug.

Let's use our newly installed jade framework and create some basic templates.

Step 1) The first step is to create a jade template. Create a file called index.jade and insert the below code. Ensure to create the file in "view" folder 

  1. Here we are specifying that the title of the page will be changed to whatever value is passed when this template gets invoked.
  2. We are also specifying that the text in the header tag will get replaced to whatever gets passed in the jade template.

var express=require('express');
var app=express();
app.set('view engine','jade');
app.get('/',function(req,res)
{
res.render('index',
{title:'Guru99',message:'Welcome'})
});
var server=app.listen(3000,function() {});

Code Explanation:

  1. The first thing to specify in the application is "view engine" that will be used to render the templates. Since we are going to use jade to render our templates, we specify this accordingly.
  2. The render function is used to render a web page. In our example, we are rendering the template (index.jade) which was created earlier.
  3. We are passing the values of "Guru99" and "Welcome" to the parameters "title" and "message" respectively. These values will be replaced by the 'title', and 'message' parameters declared in the index.jade template.

If the command is executed successfully, the following Output will be shown when you run your code in the browser.

Output:

From the output,

  • We can see that the title of the page gets set to "Guru99" and the header of the page gets set to "Welcome."
  • This is because of the jade template which gets invoked in our node js application.

Summary

  • The express framework is the most common framework used for developing Node js applications. The express framework is built on top of the node.js framework and helps in fast-tracking development of server-based applications.
  • Routes are used to divert users to different parts of the web applications based on the request made. The response for each route can be varied depending on what needs to be shown to the user.
  • Templates can be used to inject content in an efficient manner. Jade is one of the most popular templating engines used in Node.js applications.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

Node.js 12: The future of server-side JavaScript

Getting Started With Express

MongoDB, Express, Vue.js 2, Node.js (MEVN) and SocketIO Chat App

WebSocket + Node.js + Express — Step by step tutorial using Typescript


Introduction to Node & Express

Introduction to Node & Express

Get started on your full-stack developer career by learning Node & Express the most popular Javascript web framework in the world

Since its introduction in 2009, Node JS has exploded in popularity and is now the industry standard for JavaScript-based server systems. In conjunction with the popular web framework Express JS, Node has made it possible for full stack developers to create scalable, fast, sophisticated web apps using one primary language on both the front end and back end - JavaScript. In this intro series, we break down the basics of a Node/Express application.

The 10-part series covers:

  • Project Structure
  • Static Assets
  • Templating Engines
  • Dynamic Requests
  • Handling POST data
  • Rendering Dynamic Data
  • Styling and Images
  • Middleware
  • Deployment

What you'll learn

  • Create a simple web app using Node JS, Express, Bootstrap and jQuery then deploy to a staging environment.

Handle CORS issue in Angular 8 and Node/Express Applications

Handle CORS issue in Angular 8 and Node/Express Applications

In this tutorial, we will learn to handle CORS (Cross-Origin Resource Sharing) issue in Angular 8/9 and Node/Express Applications. To solve CROS related issues in Angular, we will manage proxy configuration settings.

In this tutorial, we will learn to handle CORS (Cross-Origin Resource Sharing) issue in Angular 8/9 and Node/Express Applications. To solve CROS related issues in Angular, we will manage proxy configuration settings.

To sort out CORS related problems in Node/Express Applications, we will be using a third-party plugin called cors and some backend settings.

Table of Contents

  1. Introduction to CORS
  2. Fixing CORS Issue in Angular 8/9
  3. Enable CORS in Node/Express Server
  4. Conclusion
Introduction to CORS

Cross-origin resource sharing (CORS) is a standard that manages communication between 2 or multiple domains.

CORS is a mechanism for accessing data on various domains, that data type could be images, stylesheets, js scripts, iframes, and videos. This mechanism is used for sharing restricted resources on a web page asked from a different domain.

Fixing CORS Issue in Angular 8/9

Angular server by default serves on localhost:4200 (PORT 4200) and suppose if your backend server is working on different port or domain, then the CORS issue will inevitably occur.

Enable CORS with Proxy Configuration Settings in Angular.

Now, we are setting proxy in backend. Let’s say we have a backend server working on http://localhost:3000/api and we want to pass all the API calls to http://localhost:4200/api backend server.

To enable CORS via proxy configuration, we need to generate a src/proxy.conf.json file inside the Angular root folder and also place the following code inside of it.

We used the secure property to enable the deliberate use of SSL.

We defined logLevel property, to verify whether or not our proxy is running correctly.

In order to explore more about proxy configuration please refer to proxy to backend article.

{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug"
    }
}

Define Proxy Configuration values in angular.json

To register a proxy configuration, we need to go to the angular.json file and place the following code inside the serve/options. It will set the src/proxy.conf.json file in our Angular app.

"architect": {
    "serve": {
            "builder": "@angular-devkit/build-angular:dev-server",
            "options": {
                "browserTarget": "project-name:build",
                "proxyConfig": "src/proxy.conf.json"
            },
          }
}

Now, you are all set to start dev server with current proxy configuration, run the given below command. Please restart the server if you make any update in your proxy conf file.

ng serve --open
Enable CORS in Node/Express Server

Now, we will learn how to enable CORS in the Express and Node js app. We will look at one of the most straightforward methods to configure CORS in the express by using a third-party package.

You can run the following command to add the cors package in node/express backend.

npm install cors --save

Next, you can add the below code to enable cors in Express server.

// server.js

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

/* server configuration here */

Finally, CORS is enabled in the node server.

The Access-Control-Allow-Origin: * header will be rendered when any request is made to your application. This header chooses which origin are authorized to access the server resources with CORS.

Here * wildcard allots access from any source.

Conclusion

Finally, we have completed how to solve the CORS issue in Angular 8/9 and Express/Node server. To enable CORS in Angular, we learned how to configure Proxy Configuration. Other than that, we also learned how to install and configure CORS configuration in the Node server using a third-party plugin.