I provided you my favourite.js, store-controller.js, favourite.ejs, home-list.ejs and…
- User
I provided you my favourite.js, store-controller.js, favourite.ejs, home-list.ejs and app.js file below respectively help me to resolve the issue of when I click on add to favourite on home card of Homes list page then it save null in favourite.json file instead actual of homeId. // favourite.js - // Core Module const fs = require('fs'); // File System module to read/write files const path = require('path'); const rootDir = require('../utils/pathUtil');
const favouriteDataPath = path.join(rootDir, 'data', 'favourite.json');
module.exports = class Favourite {
static addToFavourite(homeId, callback) { Favourite.getFavourites(favourites => { // registeredHomes.push(this); if (favourites.includes(homeId)) { console.log('Home already in favourites'); return callback(); } else { favourites.push(homeId); fs.writeFile(favouriteDataPath, JSON.stringify(favourites), callback); } }); }
static getFavourites(callback) { fs.readFile(favouriteDataPath, (err, data) => { callback(!err ? JSON.parse(data) : []); }); } };
// store-controller.js - const Favourite = require("../models/favourite"); const Home = require("../models/home");
exports.getIndex = (req, res, next) => { Home.fetchAll((registeredHomes) => { res.render("store/index", { registeredHomes: registeredHomes, pageTitle: "airbnb Home", currentPage: "index", }); }); };
exports.getHome = (req, res, next) => { Home.fetchAll((registeredHomes) => { res.render("store/home-list", { registeredHomes: registeredHomes, pageTitle: "Homes List", currentPage: "home", }); }); };
exports.getBookings = (req, res, next) => { res.render("store/bookings", { pageTitle: "My Bookings", currentPage: "bookings", }); };
exports.getFavouriteList = (req, res, next) => { Home.fetchAll((registeredHomes) => { res.render("store/favourite-list", { registeredHomes: registeredHomes, pageTitle: "My Favourites", currentPage: "favourites", }); }); };
exports.postAddToFavourite = (req, res, next) => { console.log("Came to add to favourite ",req.body); Favourite.addToFavourite(req.body.homeId, error => { if(error){ console.log("Error while marking favourite:", error); // res.redirect("/home"); } res.redirect("/favourites"); }) }
exports.getHomeDetails = (req, res, next) => { const homeId = req.params.homeId; Home.findById(homeId, (home) => { if (!home) { console.log("Home not found with id:", homeId); res.redirect("/home"); } else{ res.render("store/home-detail", { home: home, pageTitle: "Home Details", currentPage: "home", homeId: homeId, }) } }); };
// favourite.ejs - <form action="/favourites" method="POST">Add to Favourite
<%- include('../partials/head') %>
// External Module const express = require('express');
//Local Module const storeRouter = require("./routes/storeRouter"); const hostRouter = require("./routes/hostRouter"); const rootDir = require("./utils/pathUtil"); const errorController = require("./controllers/errors");
const app = express();
app.set('view engine', 'ejs'); app.set('views', 'views');
app.use(express.urlencoded()); app.use(storeRouter); app.use("/host", hostRouter);
app.use(express.static(path.join(rootDir, 'public')))
app.use(errorController.pageNotFound);
const PORT = 3000; app.listen(PORT, () => { console.log(
Server running on address http://localhost:${PORT}); }); - Assistant
Root cause
–––––––––––
The controller expects the value to be sent in the field homeId:Favourite.addToFavourite(req.body.homeId, …)…but the form actually sends the value in a field called id:
<input type="hidden" name="id" value="<%= home.id %>">Because
req.body.homeIdis therefore undefined, JSON serialisation converts theundefinedentry intonull, so you end up with[null](or severalnulls) infavourite.json.Fix
–––
Make the names line-up. Either change the controller to readreq.body.id, or— the more descriptive option—change the hidden input tohomeId.Updated
views/partials/favourite.ejs<form action="/favourites" method="POST"> <input type="hidden" name="homeId" value="<%= home.id %>"><!-- <<< changed --> <button type="submit" class="bg-green-300 p-2 hover:bg-green-500"> Add to Favourite </button> </form>Nothing else in your back-end code has to change; with the correct field name in place
req.body.homeIdwill now contain something like"h123"(or whateverhome.idis) andfavourite.jsonwill look e.g. like:["h123", "h357"](Optional) small clean-ups
-
Body-parser
// before your routers app.use(express.urlencoded({ extended: false }));You already call
express.urlencoded(); passingextended:falseis the usual pattern and makes intentions clear. -
favourite.js– make sure the directory exists the first time you run the app or wrapfs.writeFileinfs.mkdirif needed.
That’s it—after renaming the hidden input, “Add to Favourite” will store the actual
homeIdinstead ofnull. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.