Open In App

Job Board Platform with Node and Express.js

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

In this article, We will create a Job Board Platform using NodeJS and ExpressJS. This platform will allow users to post job listings and view job details. It will also incorporate basic and advanced calculations related to job postings, such as calculating the average salary of posted jobs or filtering jobs based on specific criteria.

Prerequisites:

Approach to Create a Job Board Platform With Node and ExpressJS:

  • Job Posting: Users can post job listings with details such as job title, company name, location, salary, etc.
  • Job Listings: Display all job listings with their details.
  • Filtering: Users can filter job listings based on criteria like location, salary range, job title, etc.
  • Calculations: Perform basic calculations such as calculating the average salary of all posted jobs.

Steps to Create the NodeJS App and Installing Module:

Step 1: Create a NodeJS project using the following command.

npm init -y

Step 2: Install Express.js and other necessary dependencies.

npm install express sequelize

Step 3: Create three folder namely “routes” , “model” and “db”.

Step 4: Create a files in each folder as routes/index.js , model/jobs.js and db/conn.js

Project Structure:

folderstrcuture

Folder structure of Job Board Platform

Example: Write the following code in respective files

  • index.js: This file sets up the Express server, defining middleware and routing.
  • routes/index.js: This file Defines routing logic for the application, including route handlers for endpoints like job listings, posting, filtering, and calculations.
  • job.js: This file Defines the data model/schema for job listings, specifying fields like job title, company name, location, salary, etc.
  • conn.js: This file Manages database connection, establishing connections using drivers like mongoose (for MongoDB) or sequelize (for SQL databases), and may include configuration options.

Javascript




// index.js
const express = require('express');
const app = express();
const port = 3000;
 
// Routes
const indexRouter = require('./routes/index');
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));
 
app.use('/', indexRouter);
 
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});


Javascript




// routes/index.js
const express = require('express');
const router = express.Router();
const Jobs = require("../model/jobs");
const { where } = require('sequelize');
 
router.get('/', (req, res) => {
  const welcomeMessage = "Welcome to our Job Board Platform! Below are the all available routes";
   
  // Function to gather information about all routes
  const getAllRoutesInfo = () => {
    const routesInfo = [];
    router.stack.forEach((route) => {
      if (route.route) {
        const routeInfo = {
          path: route.route.path,
          methods: route.route.methods
        };
        routesInfo.push(routeInfo);
      }
    });
 
    return routesInfo;
  };
 
  // Get information about all routes
  const allRoutesInfo = getAllRoutesInfo();
  res.send(`<h1>${welcomeMessage}</h1><pre>${JSON.stringify(allRoutesInfo, null, 2)}</pre>`);
});
 
// Job listings route
router.get('/showjobs', async (req, res) => {
  try {
    const alljobs = await Jobs.findAll();
 
    if (alljobs.length === 0) {
      res.status(200).json({
        message: "Oops! No Jobs Found"
      });
    } else {
      res.status(200).json({
        message: `${alljobs.length} Jobs Found`,
        Jobslist: alljobs
      });
    }
  } catch (error) {
    console.error('Error fetching jobs:', error);
    res.status(500).json({
      error: 'Internal Server Error'
    });
  }
});
 
 
// Job posting route
router.post('/postjob', async (req, res) => {
    try {
      const { jobtitle, company, location, experienceInYear, salaryInLPA, jobdescription } = req.body;
   
      const existingJobs = await Jobs.findOne({
        where: {
          jobtitle: jobtitle,
          company: company
        }
      });
 
      if (existingJobs){
      res.status(201).send({
        message: "Job Already Posted!",
        description:` ${existingJobs.jobtitle} Jobs Found from ${existingJobs.company} is already exist!`
      });
      else{
      const newJob = await Jobs.create({
        jobtitle,
        company,
        location,
        experienceInYear,
        salaryInLPA,
        jobdescription
      });
      res.status(200).send({
        message: "Job Posted Successfully!",
        data: newJob
      });
      }
      
    } catch (error) {
      console.error('Error posting job:', error);
      res.status(500).send({
        error: "Internal Server Error"
      });
    }
  });
 
  router.post('/jobs/filter', async (req, res) => {
    try {
      const { jobtitle, company, location, experienceInYear, salaryInLPA } = req.body;
   
      if (!jobtitle && !company && !location && !experienceInYear && !salaryInLPA) {
        return res.status(400).json({ error: 'At least one filter criteria is required' });
      }
      const filter = {};
      if (jobtitle) filter.jobtitle = jobtitle;
      if (company) filter.company = company;
      if (location) filter.location = location;
      if (experienceInYear) filter.experienceInYear = experienceInYear;
      if (salaryInLPA) filter.salaryInLPA = salaryInLPA;
      const filteredJobs = await Jobs.findAll({ where: filter });
      return res.status(200).json({
        message: `${filteredJobs.length} Filtered Jobs Found`,
        jobs: filteredJobs
      });
    } catch (error) {
      console.error('Error filtering jobs:', error);
      return res.status(500).json({ error: 'Internal Server Error' });
    }
  });
   
 
router.get('/jobs/calculate', async (req, res) => {
  try {
    const allJobs = await Jobs.findAll();
 
    if (allJobs.length === 0) {
      res.status(200).json({
        message: "No jobs available for calculations"
      });
    } else {
      const totalSalaries = allJobs.reduce((sum, job) => sum + job.salaryInLPA, 0);
      const averageSalary = totalSalaries / allJobs.length;
 
      res.status(200).json({
        message: "Calculation results",
        totalJobs: allJobs.length,
        averageSalary: averageSalary
      });
    }
  } catch (error) {
    console.error('Error performing calculations on jobs:', error);
    res.status(500).json({
      error: 'Internal Server Error'
    });
  }
});
 
module.exports = router;


Javascript




db/conn.js
const {Sequelize} = require("sequelize")
const sequelize = new Sequelize("jobdb","root","", {host:"localhost",dialect:"mysql"})
 
 
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection to database has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });
 
 
module.exports = sequelize


Javascript




model/jobs.js
const { DataTypes } = require("sequelize");
const sequelize = require("../db/conn");
 
const Jobs = sequelize.define("jobs",{
    jobtitle : { type: DataTypes.STRING, allowNull: false },
    company: { type: DataTypes.STRING, allowNull: false },
    location: { type: DataTypes.STRING, allowNull: false },
    experienceInYear: { type: DataTypes.INTEGER, allowNull: false },
    salaryInLPA: { type: DataTypes.INTEGER, allowNull: false },
    jobdescription: { type: DataTypes.STRING, allowNull: false }
});
 
sequelize.sync().then(() => {
    console.log('user table created successfully!');
     
 }).catch((error) => {
    console.error('Unable to create table : ', error);
 });
module.exports = Jobs;


Start your server using the following command.

node index.js

Output:

output

Job Board Platform Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads