Having an issue with the "post" and "get" functions, I am unable to make any changes to my employee table, whether it be adding

My current project involves building an app with a registration form and a login feature to access an employees table displaying their information along with the date above the table. The databases are all set up, but I am encountering issues when trying to add or delete employees. Whenever I attempt to add a new employee or delete one by checking the checkbox, the app crashes and displays an error message saying that it cannot GET.

1. Below is the code for the registration form located in REGISTER.EJS:

<form action="/register" method="post">
    <h1 class="h3 mb-3 fw-normal">Please sign in</h1>

    <div class="form-floating">
        <input type="email" class="form-control" name="email" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90fef1fdf5d0f5e8f1fde0fcf5bef3fffd">[email protected]</a>">
        <label for="floatingInput">Email address</label>
    </div>
    <div class="form-floating">
        <input type="password" class="form-control" name="password" placeholder="Password">
        <label for="floatingPassword">Password</label>
    </div>

    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> Remember me
        </label>
    </div>
    <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">&copy; Employees App</p>
</form>

2. Here is the code for the table form located in LIST.EJS:

 <div class="box" id="heading">
     <h1> <%= currentDate %></h1>
    </div>

    <div class="box">

        <% newListEmployee.forEach(function(employee){ %>
        <form action="/delete" method="post">
         <div class="item">
            <input type="checkbox" name="deleting" value="<%= employee._id %>" onChange="this.form.submit()">
            <p>Names: <b><%= employee.employeeNames %></b></p>
            <p>Address: <b><%= employee.employeeAddress %></b></p>
            <p>Phone number: <b><%= employee.employeePhone %></b></p>
            <p>Salary: <b><%= employee.employeeSalary %></b></p>
         </div>
        </form>
        <% }) %>

    <form action="/list" method="post"gt;
        <input type="text" name="Names" placeholder="Employee names:" autocomplete="off">
        <input type="text" name="Address" placeholder="Address:" autocomplete="off">
        <input type="text" name="Phone" placeholder="Phone number:" autocomplete="off">
        <input type="text" name="Salary" placeholder="Salary:" autocomplete="off">

        <button type="submit" name="button">Add</button>
    </form>
    </div>

3. Lastly, here is the issue in APP.JS where I make the requests:

app.get("/home", function (req, res) {
res.render("home");
});

app.get("/register", function (req, res) {
res.render("register");
});

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


app.post("/register", function (req, res){
const newUser = new User({
    email: req.body.email,
    password: req.body.password
});
newUser.save(function (err){
    if (err) {
        console.log(err);
    } else {

            let today = new Date();
            let options = {
                weekday: "long",
                day: "numeric",
                month: "long"
            };

            let day = today.toLocaleDateString("en-US", options);

            employeeRegistration.find({}, function (err, foundEmployees) {

                if (foundEmployees.length === 0) {
                    employeeRegistration.insertMany(defaultEmployees, function (err) {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log("Successfully added new employee to DB.");
                        }
                    });
                    res.redirect("/list");
                } else {
                    res.render("list", {
                        currentDate: day,
                        newListEmployee: foundEmployees
                    });
                }
            });
        }
    });
});

app.post("/list", function (req, res){
 const employeeName = req.body.Names;
const employeeAddresses = req.body.Address;
const employeePhoneNumber = req.body.Phone;
const employeeSalary = req.body.Salary;

const employee = new employeeRegistration({
    employeeNames: employeeName,
    employeeAddress: employeeAddresses,
    employeePhone: employeePhoneNumber,
    employeeSalary: employeeSalary
});

employee.save();

res.redirect("/list");
});

app.post("/delete" ,function (req, res){
const checkedEmployeeId = req.body.deleting;

employeeRegistration.findByIdAndRemove(checkedEmployeeId, function (err){
    if (!err) {
        console.log("You deleted checked employee!");
        res.redirect("/list");
    }
});
});

In this project, I am using JavaScript, Node.js, Express.js, and EJS. There seems to be a disconnect between my POST and GET requests, causing the application to crash unexpectedly. I need to troubleshoot and fix this issue to ensure smooth functionality.

Answer №1

The issue has been resolved successfully. I will share the solution here for reference.

I made a modification in the code within the APP.JS file, replacing the code snippet above this one.

app.get("/", function (req, res) {
res.render("home");
});

app.get("/register", function (req, res) {
res.render("register");
});

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

// More routes and functionalities are written here...
... 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Should I create a MobX store for every page in my application?

I am currently in the process of developing a single-page application using ReactJS and MobX on the frontend (running on port 3000), while utilizing Node.js and Express for the backend API (on port 4000). As someone new to both MobX and ReactJS, I am striv ...

Using Styled Components to achieve full width for input tag in relation to its parent

I am working with an input field that has a specific width set. My goal is to increase the width of this input field to 100% by selecting it from its parent component. Is there a way to achieve this without passing an explicit width prop in the styled c ...

Tips on ensuring that the Google Maps marker remains in the center as you drag the map with the AGM component

I've implemented AGM (Angular Google Maps) in my Ionic Project to showcase Google Maps, and I'm looking to have the marker stay centered on the map even when it is dragged. Is there a way to achieve this with AGM? Please let me know if I have mad ...

Customize the number of slides in Glide.js after navigating using the controls

I have incorporated a glide JS carousel to display content in a carousel format. The documentation for this repository can be found on their official website as well as on Github. Here is my current code snippet: jQuery( window ).load(function() { va ...

Guide to Implementing i18n-iso-countries Library in React

I am currently developing a React application and attempting to utilize the i18n-iso-countries package to retrieve a countries object in English where keys represent iso codes and values represent country names. This process is straightforward in Node.js, ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Communicate with the user currently connected through socket.io by sending a message

I'm struggling to grasp how to send a message using socket.io specifically to the user who has made an HTML request. Further explanations: Server My server runs on expressJS and I utilize router.get and router.post methods to handle my application. ...

angularJS controller does not seem to be functioning properly due to a certain

var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var currentdate = yyyy + ',' + mm + ',' + dd; var appointmentDate = moment($scope.AppointmentsList[i].J).f ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...

Having trouble getting Node.js, express, socket.io, and ejs to work together?

Currently, I am working on improving my knowledge of java-script and had the idea to create a basic chat app using Express, stock.io, and ejs. Unfortunately, I am facing some challenges in getting it up and running smoothly. Below is the snippet from my ...

Stealthy access using the Facebook API log-in

I'm currently developing an app that features Facebook login functionality. I'm wondering if there's a way to keep a device authorized so that users don't have to go through the process of logging in with Facebook each time they use the ...

What is the reasoning behind using the IIFE pattern on certain straightforward member functions in three.js?

Consider the Object3D base class: rotateOnAxis: function () { // rotate object on axis in object space // axis is assumed to be normalized var q1 = new Quaternion(); return function rotateOnAxis( axis, angle ) { q1.setFromAxisA ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

To access a form element in JavaScript function, utilize the dynamic form name approach

Currently, I am facing an issue with a JavaScript alert function where I am trying to view the HTML form URL before it is submitted. Following advice from a post on StackOverflow about retrieving form submit content before submit, I attempted to implement ...

Manipulating Arrays in JavaScript: Adding and Removing Objects

let mapLayers = {}; //Create a new layer mapLayers.markers = new L.Group(); mapLayers.Name = t; layers.layer = mapLayers; An error is being thrown stating that layers.length is still 'undefined'. Can someone explain why this is happening? I ha ...

"Strategies for identifying the presence of a return value or null in jQuery AJAX

Currently, I am utilizing a jQuery post ajax request to perform an action. The page 'submit.php' sends back a JSON value, and sometimes if there is a fatal error it returns nothing. I am struggling to determine whether the ajax call returns a va ...

All submissions consistently redirect to the same page without any action taking place

I am currently in the process of creating a form that will allow me to change/update my ticket status using a select option. However, whenever I submit the form, it redirects back to the same page instead of going to the desired "status-update.php" address ...

It is important for the button size to remain consistent, regardless of any increase in text content

My goal was to keep the button size fixed, even as the text on it grows. This is the current code I am using: .button { border: none; color: white; padding: 10px 50px; text-align: center; text-decoration: none; display: inline-block; font ...

Function that can be shared between two separate jQuery files

Let's say I have two separate jQuery files, both containing the same function. I would like to create a common file where I can store this shared function and then import it into other files. For example: first.js file : window.addEventListener(&apo ...

Template for developing projects using JavaScript, HTML5, and CSS3 in Visual Studio 2013

After recently downloading Visual Studio 2013 Express for Web, I am struggling to figure out how to deploy projects that only consist of JavaScript, HTML5, and CSS3. Despite searching online for JavaScript templates and even trying to download Visual Stu ...