ould i fix this issue ? const express = require('express'); const exphbs = require('express-handlebars'); const bodyParser = require("body-parser"); const fs = require("fs"); const createError = require("http-errors"); const passport = require("passport"); const path = require("path"); const session = require("express-session"); var cookieParser = require("cookie-parser

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Topic Video
Question

 this is a nodejs page .it works well on my pc ,

i am trying to run it on heroku . the others pages are all working ,only this index page cant be work .

how could i fix this issue ?

const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require("body-parser");
const fs = require("fs");
const createError = require("http-errors");
const passport = require("passport");
const path = require("path");
const session = require("express-session");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var app = express();
app.engine('hbs', exphbs({defaultLayout: false, extname:'.hbs',}));

app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "/public")));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var userLogin = {};

app.get("/", (req, res) => {
    res.render("landing", {
        title:"landing",
    });
});


app.post("/api/login", (req, res) => {
    fs.readFile("./data.json", (err, data) => {
        var arr = [];
        if (err) {
            console.log(err);
        } else {
            if (data.toString()) {
                arr = JSON.parse(data.toString());
            }
            var s = arr.find((item) => {
                if (item.name == req.body.name) {
                    return item;
                }
            });
            if (s) {
                if (s.password == req.body.password) {
                    userLogin = req.body;
                    res.json({
                        status: "y",
                        meg: "login success",
                        data: s.name,
                    });
                } else {
                    res.json({
                        status: "err",
                        meg: "wrong password ",
                    });
                }
            } else {
                res.json({
                    status: "n",
                    meg: "no such user ",
                });
            }
        }
    });
});

app.get("/index", (req, res) => {
    if (userLogin.name) {
        fs.readFile('./books.json',function(err,data){
            if(err) {
                console.error(err);
            } else {
                var books = JSON.parse(data.toString());
                res.render("index", { username: userLogin.name, books: books });
            }
        }); 
    } else {
        res.render("login");
    }
});

app.get("/login", (req, res) => {
    res.render("login");
});

app.post("/logout", (req, res) => {
    res.render("login", {});
});

app.get("/quittolanding", (req, res) => {
    res.render("landing", {});
});

app.set("views", path.join(__dirname, "views"));

app.use(express.static(path.join(__dirname, "public")));


app.get('/books', (req, res) => {

    fs.readFile('./books.json', (err, data) => {
        if(err) {
            console.error(err);
        } else {
            let books = JSON.parse(data);
            res.json(books);
            res.end();
        }
    });
});

app.put("/borrow", (req, res) => {
    const books = req.body;

    let newdata = JSON.stringify(books, null, 2);

    fs.writeFileSync('./books.json', newdata);
    console.log('Data written to file');
    res.status(204).end();
});

app.put("/return", (req, res) => {
    const books = req.body;

    let newdata = JSON.stringify(books, null, 2);

    fs.writeFileSync('./books.json', newdata);
    console.log('Data written to file');
    res.status(204).end();
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening on:`, port));

!DOCTYPEhtmlhtmllang=enheadmetacharset=UTF-8
metaname=viewportcontent=width3Ddevice-width,initial
-scale=1.0metahttp-equiv=DX-UA-Compatiblecontent=ie
=edgelinkrel=stylesheethref=/css/style.csstitleLibraryPag
e:{{title}}/title/headbodyonload=bodyLoaded()headerah
ref=/imgsrc=/images/logo.jpg/anavulliformmethod=PO
STaction=/logoutlabelid=logName{{username}}/labelbut
tonid=logOutlILogOut/label/form/li/ul/navh4abcdabook
s/h4/headermainh1LibraryPage/hlarticleid3Dbox1h2Avail
ableBooks/h2ul{{#eachbooks}}{{#ifthis.available}}li{{@key
}}Author-{{this.author}}inputtype=checkboxname=Davaila
bleclass=availablevalue={{@key}}onclick=DavailableClick()
/li{{/if}}{{/each}}/ulbrbuttonid%=borrowdisabled%3Donclick=
borrowBook()borrow/button/articlearticleid=box2h2Ren
tedBooks/h2ul{{#eachbooks}}{{#unlessthis.available}}li{{@
key}}Author-{{this.author}}inputtype=checkboxname=ren
tedclass=rentedvalue={{@key}}onclick=rentedClick()/li{{/
unless}}{{/each}}/ulbrbuttonid%3Dreturndisabled=onclick3r
eturnBook()return/button/article/mainscriptletbooks={};
functionbodyLoaded(event){fetch('/books',{headers:{'Ac
cept':'application/json',},}).then(response=response.json
().then(response=books=response).catch(error=console
log(Errorfetchingdata!));}functionavailableClick(event){co
nstbtnBorrow=document.querySelector('#borrow');btnB
orrow.disabled3Dtrue;constavailable=document.querySel
ectorAll('.available');available.forEach(function(book){if(b
ook.checked)btnBorrow.disabled%3false;});}functionrented
Click(event){constbtnReturn=document.querySelector('#
return');btnReturn.disabled=true;constrented=document
.querySelectorAll('.rented');rented.forEach(function(book
){if(book.checked)btnReturn.disabled=false;});}functionb
orrowBook(){letchange=false;constavailable=document.
querySelectorAlI(".available');available.forEach(function(b
ook){if(book.checked){books[book.value].available=false
;change=true;}};if(change=3true){fetch('/borrow',{heade
rs:{'Accept':'application/json','Content-Type':'application
/json'},method:'PÚT',body:JSON.stringify(books)}).then(c
onsole.log(Dataupdatedsuccessfully)).catch(error=conso
le.log(error.message));}console.log(books);refreshData();
}functionreturnBook(){letchange=false;constrented=doc
ument.querySelectorAll('.rented');rented.forEach(function
(book){if(book.checked){books[book.value].available=tru
e;change=true;}});if(change=D3Dtrue){fetch('/return',{heade
rs:{'Accept':'application/json','Content-Type':'application
/json'},method:'PUT',body:JSON.stringify(books)}).then(c
onsole.log(Dataupdatedsuccessfully)).catch(error=conso
le.log(error.message));}console.log(books);refreshData();
}functionrefreshData(){constbox1=document.querySelec
tor('#box1');constbox2=document.querySelector('#box2
");letcontent='h2AvailableBooks/h2';content+='ul';for(co
nsttitleinbooks){if(books[title].available){content+ ="li';co
ntent+='${title}Author-${books[title].author}';content+=
inputtype=checkboxname=Davailableclass=availablevalu
e=${title}onclick=availableClick()`;content+=/li';}}conten
t+='/ulbrbuttonid%3Dborrowdisabled3Donclick=borrowBoo
k()borrow/buttonbr';box1.innerHTML=content;content=
'h2RentedBooks/h2';content+='ul';for(consttitleinbooks)
{if(!books[title].available){content+='li";content+='${title
}Author-${books[title].author}';content+='inputtype=che
ckboxname=rentedclass=rentedvalue=${title}onclick=re
ntedClick()';content+='/li';}}content+ ='/ulbrbuttonid%3Dre
turndisabled=onclick=returnBook()return/buttonbr';box
2.innerHTML=content;}/script/body/html
Transcribed Image Text:!DOCTYPEhtmlhtmllang=enheadmetacharset=UTF-8 metaname=viewportcontent=width3Ddevice-width,initial -scale=1.0metahttp-equiv=DX-UA-Compatiblecontent=ie =edgelinkrel=stylesheethref=/css/style.csstitleLibraryPag e:{{title}}/title/headbodyonload=bodyLoaded()headerah ref=/imgsrc=/images/logo.jpg/anavulliformmethod=PO STaction=/logoutlabelid=logName{{username}}/labelbut tonid=logOutlILogOut/label/form/li/ul/navh4abcdabook s/h4/headermainh1LibraryPage/hlarticleid3Dbox1h2Avail ableBooks/h2ul{{#eachbooks}}{{#ifthis.available}}li{{@key }}Author-{{this.author}}inputtype=checkboxname=Davaila bleclass=availablevalue={{@key}}onclick=DavailableClick() /li{{/if}}{{/each}}/ulbrbuttonid%=borrowdisabled%3Donclick= borrowBook()borrow/button/articlearticleid=box2h2Ren tedBooks/h2ul{{#eachbooks}}{{#unlessthis.available}}li{{@ key}}Author-{{this.author}}inputtype=checkboxname=ren tedclass=rentedvalue={{@key}}onclick=rentedClick()/li{{/ unless}}{{/each}}/ulbrbuttonid%3Dreturndisabled=onclick3r eturnBook()return/button/article/mainscriptletbooks={}; functionbodyLoaded(event){fetch('/books',{headers:{'Ac cept':'application/json',},}).then(response=response.json ().then(response=books=response).catch(error=console log(Errorfetchingdata!));}functionavailableClick(event){co nstbtnBorrow=document.querySelector('#borrow');btnB orrow.disabled3Dtrue;constavailable=document.querySel ectorAll('.available');available.forEach(function(book){if(b ook.checked)btnBorrow.disabled%3false;});}functionrented Click(event){constbtnReturn=document.querySelector('# return');btnReturn.disabled=true;constrented=document .querySelectorAll('.rented');rented.forEach(function(book ){if(book.checked)btnReturn.disabled=false;});}functionb orrowBook(){letchange=false;constavailable=document. querySelectorAlI(".available');available.forEach(function(b ook){if(book.checked){books[book.value].available=false ;change=true;}};if(change=3true){fetch('/borrow',{heade rs:{'Accept':'application/json','Content-Type':'application /json'},method:'PÚT',body:JSON.stringify(books)}).then(c onsole.log(Dataupdatedsuccessfully)).catch(error=conso le.log(error.message));}console.log(books);refreshData(); }functionreturnBook(){letchange=false;constrented=doc ument.querySelectorAll('.rented');rented.forEach(function (book){if(book.checked){books[book.value].available=tru e;change=true;}});if(change=D3Dtrue){fetch('/return',{heade rs:{'Accept':'application/json','Content-Type':'application /json'},method:'PUT',body:JSON.stringify(books)}).then(c onsole.log(Dataupdatedsuccessfully)).catch(error=conso le.log(error.message));}console.log(books);refreshData(); }functionrefreshData(){constbox1=document.querySelec tor('#box1');constbox2=document.querySelector('#box2 ");letcontent='h2AvailableBooks/h2';content+='ul';for(co nsttitleinbooks){if(books[title].available){content+ ="li';co ntent+='${title}Author-${books[title].author}';content+= inputtype=checkboxname=Davailableclass=availablevalu e=${title}onclick=availableClick()`;content+=/li';}}conten t+='/ulbrbuttonid%3Dborrowdisabled3Donclick=borrowBoo k()borrow/buttonbr';box1.innerHTML=content;content= 'h2RentedBooks/h2';content+='ul';for(consttitleinbooks) {if(!books[title].available){content+='li";content+='${title }Author-${books[title].author}';content+='inputtype=che ckboxname=rentedclass=rentedvalue=${title}onclick=re ntedClick()';content+='/li';}}content+ ='/ulbrbuttonid%3Dre turndisabled=onclick=returnBook()return/buttonbr';box 2.innerHTML=content;}/script/body/html
Expert Solution
steps

Step by step

Solved in 2 steps

Blurred answer
Knowledge Booster
Instruction Format
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education