Implementing multiple POST requests within a single route: A step-by-step guide

My current challenge involves implementing two POST request methods for buttons in an EJS template. So far, I have only used one POST request per route and now struggle to get both buttons to function correctly.

I have two different sets of to-do lists: one under the home route "/" identified by the key pair value list: day, and the other identified as list: "Work".

Each list has a post request that adds a new item, and the second POST request redirects to the other to-do list. These actions are triggered by submit buttons.

To address this issue, I created a third route assigned to the redirect button. This route should redirect either to the home or work list based on the current titleList value.

However, I can easily redirect from the home list to the work list, but I face trouble directing back to the home page once at the work list!

When I attempt the second redirection, the console logs a 302 status code immediately upon clicking the button.

At this stage, I believe a get request is not feasible as it would direct to nothing, leaving me unsure how to proceed further.

Being new to Node.js and Express, I seek guidance in resolving this issue.

Check out my code below:

HTML

<%- include("header") -%>    
<div class="box" id="heading">
<h1><%=listTitle%></h1>
</div>

<div class="box">
<% for (let i =0; i< newListItems.length; i++) { %>
<div class="item">
<input type="checkbox">
<p><%= newListItems[i] %></p>
</div>
<% }; %>

<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New item?" autocomplete="off">
<button type="submit" name="list" value=<%= listTitle %>>+</button>
</form>

</div>

<form class="" action="/divert" method="post">
<button type="submit" class="btn1" name="redirect" value="identify" style="width: 
100px"><%=btnName%></button>
</form> 

<%- include("footer") -%>

app.js

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");

// globals.
let items = [];
let workItems = [];
let btnIdentify = "Work";

const app = express();
app.use(bodyParser.urlencoded({extended: true}));

//Send static css file to browser.
app.use(express.static("public"));

app.set('view engine', 'ejs');
   

app.get("/", function(req, res) {
const date = new Date();
const options = {
weekday: "long",
day: "numeric",
month: "long"
};

let day = date.toLocaleDateString("en-US", options);
res.render('list', {listTitle: day, newListItems: items, btnName: btnIdentify});
});


app.post("/", function(req, res) {
let item = req.body.newItem;

if (req.body.list === "Work")  { //only uses frist word off the listTitle value.
workItems.push(item);
res.redirect("/work");
} else {
items.push(item);
res.redirect("/");
}
console.log(req.body);
})

app.get("/work", function(req,res) {

res.render("list", {listTitle: "Work list", newListItems: workItems, btnName: btnIdentify });
});

app.post("/divert", function(req,res) {
if (req.body.list !== "Work") {
res.redirect("/work");
btnIdentify = "Work";
} else if (req.body.list === "Work") {
res.redirect("/");
btnIdentify = "Home";
}
})

app.listen(3000, function() {
console.log("Server is running on port 3000")
});

Answer №1

After seeking help on here, I managed to come up with a solution through deeper thinking.

I made use of EJS markers in the redirect buttons as shown below:

<form  action=<%= resType %> method="post">

To achieve this, I included resType as a new key-value pair on the server side to be rendered in both app.get routes like so:

res.render("list", { listTitle: "Work list", newListItems: workItems, btnName: btnIdentify, resType: "/work" });

Furthermore,

res.render('list', { listTitle: day, newListItems: items, btnName: btnIdentify, resType: "/divert" });

By doing this, each time the redirect button was clicked, it would initiate a POST request to the route based on the value of resType.

Finally, all I had left to do was create two app.post methods to handle these post requests as shown below:

app.post("/work", function(req,res) {

    res.redirect("/");
    btnIdentify = "Work";

})

app.post("/divert", function(request,response) {
  if (request.body.list !== "Work") {
    response.redirect("/work");
    btnIdentify = "Home";
  }
})

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

The animation is not updating quickly enough

I'm working on a navigation bar that sticks to the top of the page. As the user scrolls down, I want the bar to shrink, and when they scroll back up, it should return to its original size. Issue: The problem I'm facing is that when the user quic ...

Learn the functionality of element focus in javascript

I'm trying to wrap my head around how element focus functions. Here are my questions:- Are there any limitations to JavaScript focus? Does it have the same permissions when executed from website code versus the debug console? Additionally, doe ...

Express is unable to provide static file hosting for a child EJS file

My current setup includes express version 3.2.5 and ejs version 0.8.4 I am looking to serve the stylesheet stylesheets/style.css In my app.js, I have implemented the following: app.use(express.static(path.join(__dirname, 'public'))); app.u ...

Verify that the value being returned is in the form of a promise

Provided an angular controller containing the following function: this.checkResponse = function (response) { if (response.success === true) { return $q.resolve(response); } else { return $q.reject(response); } }; I am looking to test with J ...

Suggestions for selecting a reliable middleware for uploading files in a Node Express application, specifically compatible with inversify-express-utils controllers

Currently, I am collaborating on a project at my job where we are using Typescript and ExpressJs with inversify-express-utils for our controllers to manage all the endpoints. One of my assignments is to implement a backend endpoint for file uploads capable ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

RouterLinkActive is functional within ngFor

Preferably seeking a JavaScript solution, with Angular2 as the top choice I am currently attempting to generate my navigation bar dynamically based on an API call. The main issue I'm facing is ensuring that the parent li has an active class when ano ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

Creating DIV's with Equal Heights Using AngularJS ng-repeat

I'm currently facing an issue with aligning two side-by-side divs to the same height when the content is generated using an ng-repeat function. Using flexbox is causing responsiveness issues, and I'm unsure of the appropriate time to call a jQuer ...

The UI-SELECT feature in angular-js does not seem to be displaying

I've added the necessary ui-select js and css files to my page : <link href="assets/plugins/ui-select/select.min.css" rel="stylesheet" type="text/css" <script src="assets/plugins/ui-select/select.min.js" tyle="text/javascript" </script> ...

Angular's directives do not trigger the 'viewContentLoaded' event

I recently created a 'light-gallery' directive that relies on the jquery.lightgallery.js plugin to initialize the $.fn.lightGallery() functions. It is crucial for these functions to be executed after the directive template has been compiled and l ...

My goal is to store the received response in an array within an object

const data = [ { id: 1, user_name: 'john', phone_number: 5551234567 }, { id: 2, user_name: 'jane', phone_number: 5559876543 }, { id: 3, user_name: 'doe', ...

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

If the input field is empty, there is no action required. However, if the input field contains a value, it must be checked to ensure it is a numeric value. If

I'm attempting to create a form that automatically adds up input fields when they lose focus, displaying the sum in an inactive "Total:" field. I want to avoid running any calculations if a user clicks on an input field and then moves away without ent ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

React higher order component (HOC) DOM attributes are causing the error message 'Unknown event handler property' to be triggered

I recently created a Higher Order Component (HOC) using recompose, but I'm encountering a React Warning every time the props are passed down. Warning: Unknown event handler property `onSaveChanges`. It will be ignored. All my properties with a speci ...

Secure your desktop application with OAuth by enabling HTTPS on localhost

I am currently in the process of developing a desktop application that integrates with Spotify's oauth api using the implicit grant flow as outlined here: My plan is to incorporate an "Authenticate" button, which when clicked will open the user' ...