Open In App

Movie Recommendation System with Node and Express.js

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Building a movie recommendation system with Node and Express will help you create personalized suggestions and recommendations according to the genre you selected. To generate the recommendation OpenAI API is used. In this article, you will see the step-wise guide to build a Movie recommendation system.

Output Preview: Let us have a look at how the final output will look like.

2-(online-video-cuttercom)

Prerequisites :

Approach to create Movie Recommendation System:

  • Input processing: Analyze user preferences and input using the OpenAI API.
  • Personalized Recommendations: Utilize the OpenAI API to generate movie recommendations based on user preferences.
  • Responsive Design: Ensure the application is responsive across various devices.
  • User interface: Provide a user-friendly interface to interact with the system.
  • Error Handling: Implement robust error handling to enhance user experience

Steps to create the project:

Step 1: Set Up Your Development Environment:

  • Install Node.js: If you haven’t already, download and install Node.js from the official website (https://nodejs.org/). Follow the installation instructions for your operating system.
  • Verify Installation: After installation, open a terminal (or command prompt) and run node -v and npm -v to ensure Node.js and npm (Node Package Manager) are installed correctly.

Step 2: Set Up Project Structure:

Create a new directory for your project and navigate into it:

mkdir movie-recommendation
cd movie-recommendation

Step 3: Install Dependencies:

You’ll need to install Express.js and Axios for making HTTP requests:

npm init -y
npm install express axios dotenv

Folder Structure:

Screenshot-2024-02-29-130058

The updated Dependencies in package.json file will look like:

"dependencies": {
"axios": "^1.6.7",
"dotenv": "^16.4.5",
"express": "^4.18.3"
}

Example: Create the files as suggested in folder structure and add the following code.

HTML




<!-- public/index.html -->
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Movie Recommendation</title>
</head>
 
<body>
    <div class="container">
        <br>
        <h1 class="text-center">Movie Recommendation System</h1>
        <div class="form-group">
            <label for="userInput">Enter Your Preferences:</label>
            <textarea class="form-control" id="userInput" rows="3"></textarea>
        </div>
        <button type="button" class="btn btn-primary" id="recommendBtn">
            Get Movie Recommendation
        </button>
        <div id="recommendation" class="mt-3"></div>
        <div id="loader" class="mt-3 text-center" style="display: none;">
            <div class="spinner-border text-primary" role="status">
                <span class="sr-only">Loading...</span>
            </div>
        </div>
    </div>
 
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="script.js" defer></script>
</body>
 
</html>


Javascript




// public/script.js
 
document.addEventListener("DOMContentLoaded", () => {
    const recommendBtn = document.getElementById("recommendBtn");
    const userInput = document.getElementById("userInput");
    const recommendationDiv = document.getElementById("recommendation");
    const loaderDiv = document.getElementById("loader");
 
    recommendBtn.addEventListener("click", async () => {
        const inputText = userInput.value.trim();
 
        if (inputText === "") {
            alert("Please enter your preferences.");
            return;
        }
 
        // Show loader
        loaderDiv.style.display = "block";
 
        try {
            const response = await axios.get
                (`/recommend?input=${inputText}`);
            const recommendedMovie = marked.parse(response.data);
 
            if (recommendedMovie) {
                recommendationDiv.innerHTML = `
                      <h3>Recommended Movie:</h3>
                      <p>${recommendedMovie}</p>
                  `;
            } else {
                recommendationDiv.innerHTML = `
                      <p>No Movie recommendation available.</p>
                  `;
            }
        } catch (error) {
            console.error(error);
            recommendationDiv.innerHTML = `
                  <p>An error occurred while fetching Movie recommendation.</p>
              `;
        } finally {
            // Hide loader
            loaderDiv.style.display = "none";
        }
    });
});


Javascript




//server.js
 
const express = require("express");
const axios = require("axios");
const dotenv = require("dotenv");
const { OpenAI } = require("openai");
 
dotenv.config();
 
const app = express();
const PORT = process.env.PORT || 3000;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
 
const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
 
app.use(express.static("public"));
 
app.get("/recommend", async (req, res) => {
    try {
        const userInput = req.query.input;
        const completion = await openai.chat.completions.create({
            messages: [
                { role: "system", content: "You are helpful in recommending Movies." },
                { role: "user", content: userInput + "\n list out all Movies" },
            ],
            model: "gpt-3.5-turbo",
        });
        const recommendedMovie = completion.choices[0].message.content;
        res.send(recommendedMovie);
    } catch (error) {
        console.error(error);
        res.status(500).send("An error occurred while processing your request.");
    }
});
 
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


.env file: This file will contain your environment variables, including your OpenAI API key.

PORT=3000
OPENAI_API_KEY=your_openai_api_key_here

Run the following command to start the server:

node server.js

Output:

2-(online-video-cuttercom)



Similar Reads

Movie Recommendation System using Django
In this article, we will guide you through the process of creating a comprehensive Movie Recommendation System with the added functionality of user authentication. By incorporating a login system, users can create accounts, personalize their preferences, and access movie recommendations tailored to their tastes. This combination of user authenticat
8 min read
Book Recommendation System using Node and Express.js
The Book Recommendation System aims to enhance the user's reading experience by suggesting books tailored to their interests and preferences. Leveraging the power of machine learning and natural language processing, the system will analyze user inputs and recommend relevant books from a database. In this project, we will develop a Book Recommendati
4 min read
Movie recommendation based on emotion in Python
Movies that effectively portray and explore emotions resonate deeply with audiences because they tap into our own emotional experiences and vulnerabilities. A well-crafted emotional movie can evoke empathy, understanding, and self-reflection, allowing viewers to connect with the characters and their journey on a profound level. Sentiment Analysis W
5 min read
Project Idea | Songs Recommendation System in Android
Project Title: Songs Recommendation System in Android Introduction: We all know that in today's era internet is expanding very much and as a result, the data, as well as other importation which we want to show to a particular user, becomes difficult for the techs to recommend to their users. So here the concept of Recommendation Systems come into p
2 min read
Project Idea | Recommendation System based on Graph Database
The main objective of this project is to build an efficient recommendation engine based on graph database(Neo4j). The system aims to be a one stop destination for recommendations such as Movies, Books, Blog. Features: Movie Module: a) Rate Movies (1-5) rating. b) Get Movie Recommendations using collaborative-filtering based on ratings. c) Get Movie
1 min read
How to Design Movie Telegram Bot using Node.js ?
Telegram bot API can be used to create a chatbot that returns the complete details of movies, web series, and Tv series by sending the name of the movie or series as a command. Telegram provides a bunch of API’s methods to perform different functions. The telegram bot can be used to know the complete details of the movie without going to other webs
3 min read
Restaurant Recommendation using MERN
This article is about Restaurant Recommendations using the MERN (MongoDB, Express.js, React.js, Node.js) stack. This project displays a list of restaurants to the users. Users can apply filters like location, cuisines, and ratings based on filters applied by the user, the user gets recommended specific restaurants. Preview of final output: Let us h
9 min read
Blog Post Recommendation using Django
In this article, we will guide you through the creation of a blog post recommendation system using Django. Our article covers the integration of a user-friendly login system with a registration form, ensuring a seamless experience for your website visitors. Additionally, we have implemented a sophisticated search functionality that allows users to
10 min read
Restaurant Recommendation App using MEAN
In this article, we'll explore the process of building a restaurant recommendation application using Angular for the client side and Node.js with Express for the server side. This application will allow users to search for restaurants based on location, cuisine, and rating, providing them with a curated list of dining options. Project Preview: Prer
10 min read
Task Management System using Node and Express.js
Task Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend interface part in which we can add, delete, and update
25 min read