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

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...
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...
Create a Java application that will prompt the user for the first name of 6 friends...
Create a Java application that will prompt the user for the first name of 6 friends in any order and store them in an array. First, output the array unsorted. Next, sort the array of friends and then output the sorted array to the screen. Be sure to clearly label the output. See the example program input and output shown below. It does not have to be exactly as shown in the example, however it gives you an idea of...
Java Code: Write an application that takes in user input. (Name, Age, and Salary) ------ Write...
Java Code: Write an application that takes in user input. (Name, Age, and Salary) ------ Write an application that includes a constructor, user input, and operators.
Assignment: Create data file consisting of integer, double or String values. Create unique Java application to...
Assignment: Create data file consisting of integer, double or String values. Create unique Java application to read all data from the file echoing the data to standard output. After all data has been read, display how many data were read. For example, if 10 integers were read, the application should display all 10 integers and at the end of the output, print "10 data values were read" My issue is displaying how many integers were read and how many strings...
Using the main function’s arguments, create a program that takes in a person’s name, their home...
Using the main function’s arguments, create a program that takes in a person’s name, their home town/location, and cell number then prints out the following message: Sample run 1: Java lab01_task03 Sililo Uis 0819876543 Output:   Contact successfully saved !! Contact Name : Sililo @ Uis Home number: 0819876543
Create a program that when run, prompts the user to enter a city name, a date,...
Create a program that when run, prompts the user to enter a city name, a date, the minimum temperature and the maximum temperature. Calculate the difference between the maximum temperature and the minimum temperature. Calculate the average temperature based on the minimum and maximum temperature. Print out the following: City name today's Date minimum temperature maximum temperature average temperature difference between minimum and maximum The following is a sample run, user input is shown in bold underline. Enter City Name:...
Needed in C++ In this assignment, you are asked to create a class called Account, which...
Needed in C++ In this assignment, you are asked to create a class called Account, which models a bank account. The requirement of the account class is as follows (1) It contains two data members: accountNumber and balance, which maintains the current account name and balance, respectively. (1) It contains three functions: functions credit() and debit(), which adds or subtracts the given amount from the balance, respectively. The debit() function shall print ”amount withdrawn exceeds the current balance!” if the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT