Question

In: Computer Science

For this assignment, You will create a NodeJS application which takes a city name as an...

For this assignment, You will create a NodeJS application which takes a city name as an input in its pug template. using openweathermap API, you should get the weather of that particular city and displays that information to a new pug template. You should also store the results in a file in your directory. Following are the detailed requirements.

Your application should start with a pug template (similar to HTML page) which has a form with an input field and label to accept the city name and a button on clicking which we can send a GET request to the server.

Your server code (Back-end) should be able to take this city name, make an API call to the openweathermap API.

You should be able successfully to establish the API call and retrieve data from it.

You should also be able to display this data in a new pug template.

This same pug template will also have a form in which we should be able to enter the data you that we received from openweathermap.

On entering and submitting that data, You should be able to make a POST request to your back-end.

Your back-end code should write those values to a file in your local directory using async and fs.

Openweathermap API documentation: https://openweathermap.org/api

Solutions

Expert Solution

CODE:

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//telling app to use inde.js for routes
app.use('/', index);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js file

var express = require('express');
var router = express.Router();
var request=require('request');
const fs = require('fs')

//function to write in a file
const writeFile = (path, data, opts = 'utf8') =>
    new Promise((res, rej) => {
        fs.writeFile(path, data, opts, (err) => {
            if (err) rej(err);
            else res()
        })
    });

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/city',function (req,res,next) {
   console.log(req.query.city);
   //get request
    request.get('https://samples.openweathermap.org/data/2.5/weather?q='+req.query.city+'&appid=b6907d289e10d714a6e88b30761fae22',function(err,res2){
        if(err)
          throw new Error(err);
        else {
            //sending data to the new pug template named post.jade
          res.render('post', {data: res2.body});
          //console.log(res2.body)
        }
    });
});

router.post('/write',function (req,res,next) {
    console.log(req.body.write);
    async function write(data) {
        await writeFile('/home/sys1108/Desktop/weather.json',data,)
        res.render('index',{title:"data write success"})
    }
    write(req.body.write)
});

module.exports = router;

index.jade

extends layout

block content
  h1= title
  form(name="weather-report", method="get", action="/city")
    div.input
      span.label City Name:
      input(type="text", name="city")
    div.actions
      input(type="submit", value="Submit")

post.jade

extends layout

block content
    h2="Response from the Api"
    p #{data}

    h2="copy the above response and paste in below box to make a post request"

    form(name="weather-report", method="post", action="/write")
        div.input
            span.label
            textarea(name="write", cols="40", rows="5")
        div.actions
            input(type="submit", value="Submit")

layout.jade

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

error.jade

extends layout

block content
  h1= message
  h2= error.status
  pre #{error.stack}

============================================

project structure and files:

app.js file

index.js file

index.jade

post.jade

layout.jade

error.jade

output:


Related Solutions

Assignment 5: Roman Numerals Assignment 5 You must create an application that takes two integer values,...
Assignment 5: Roman Numerals Assignment 5 You must create an application that takes two integer values, adds them together, and then displays the result of that expression as a roman numeral. Create a two Python scripts: 1. Name your first script roman_numerals.py 2. Name your second script user_input.py 3. The goal of this projects is to practice the principles of abstraction while adding in an element of selection. How much you abstract your code is up to you, but you...
Create a project for this assignment. You can name it assignment02 if you wish. Download the...
Create a project for this assignment. You can name it assignment02 if you wish. Download the database file pizza-190807A.sqlite into the top level of the project. Create the pizza_services.py module first and put in the code given in the assignment. Using this code ensures that you can use the services in a similar way to the example. The assignment suggests adding a method customer to the class. This will return a list of rows from the customer table in the...
In C# Create a windows application which accepts the month number and displays the month name...
In C# Create a windows application which accepts the month number and displays the month name in a label.   Use a nested if... else statement to determine the month name. For months not in the range 1-12 display the message "Not a valid month"
Database Application Development Project/Assignment Milestone 1 (part 1) Objective: In this assignment, you create a simple...
Database Application Development Project/Assignment Milestone 1 (part 1) Objective: In this assignment, you create a simple HR application using the C++ programming language and Oracle server. This assignment helps students learn a basic understanding of application development using C++ programming and an Oracle database Submission: This Milestone is a new project that simply uses what was learned in the SETUP. Your submission will be a single text-based .cpp file including your C++ program for the Database Application project/assignment. The file...
Create java class with name MyClass1 Instructions for MyClass1 For this portion of the assignment you...
Create java class with name MyClass1 Instructions for MyClass1 For this portion of the assignment you will need to create a java class of your own to model some objects in the real world or your own imagination. your classes should have at least three instances variables, accessor and mutator methods for each of those instance variables, one constructor method of any type, as well as an overridden toString method that will display every field value as part of a...
In this assignment, which continues to build on last week's assignment, you will create a mind...
In this assignment, which continues to build on last week's assignment, you will create a mind map identifying the steps in the training process for a CRM program to help you understand the important role training plays in an organization. It further helps you understand the importance of training as you explore how training is designed, delivered, and measured for success I need more info on what a CRM is and Which training evaluation methods would you recommend to assess...
Create a C# console application (do not create a .NET CORE project) and name the project....
Create a C# console application (do not create a .NET CORE project) and name the project. Generate two random integers, each between 1 and 50, that you will be adding together to test the user's ability to perform the addition operator. Display the numbers in the console, such as:             7 + 22 = ? Once the user provides their answer, check to see if it is correct and if not, tell them sorry, please try again. If their answer...
Create a C# console application (do not create a .NET CORE project) and name the project...
Create a C# console application (do not create a .NET CORE project) and name the project TuitionIncrease. The college charges a full-time student $12,000 in tuition per semester. It has been announced that there will be a tuition increase by 5% each year for the next 7 years. Your application should display the projected semester tuition amount for the next 7 years in the console window in the following format:             The tuition after year 1 will be $12,600. Note:...
Create a C# console application (do not create a .NET CORE project) and name the project...
Create a C# console application (do not create a .NET CORE project) and name the project TimeToBurn. Running on a particular treadmill, you burn 3.9 calories per minute. Ask the user how many calories they wish to burn in this workout session (this is their goal). Once they tell you, output on the console after each minute, how many calories they have burned (e.g. After 1 minute, you have burned 3.9 calories). Keep outputting the total amount of calories they...
1) Create a table “college” that has as attributes name, city name, state/province/region name, country name,...
1) Create a table “college” that has as attributes name, city name, state/province/region name, country name, and year in which the college was established as well as an ID as primary key. Insert records for 5 colleges of your choice, including one or more you have attended. 2) Create a table “student” that has as attributes first name, last names, and college ID for students, and insert the names of yourself and friends who attended one or more colleges together...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT