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
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](/v2/_next/image?url=https%3A%2F%2Fcontent.bartleby.com%2Fqna-images%2Fquestion%2Fd7770d6e-352d-49c5-bb02-13e122a27c4b%2Fa28bdd44-2a54-4cc3-b1bc-63ebf9d61bbf%2Fg38fxzk_processed.jpeg&w=3840&q=75)

Step by step
Solved in 2 steps









