Updating the route in Express.js/Node.js to redirect form submission from `/page` to `/page/<input>`.Is this fine for you

How can I redirect a user from /page to /page/:nickname in Express after they enter a nickname and click submit?

This is my code:

// app.js

app.get("/page", (request, response) => {
    response.render("page"); 
});

app.get("/page/:nickname", (request, response) => {
    response.render("page", {
        nickname: request.params.nickname
    });
});
// page.pug
extends layout

block content
    // render when on "/page" and "/page/:nickname"
    form(method="post" action="???")
        input(placeholder="Player nickname" type="text")
        button.btn.btn-success(type="submit")
            |Search
    if nickname
        // render if on "/page/:nickname"

Answer №1

When approaching this issue, you have two options:

Server-side

To handle this on the server side, make sure the form method is set to GET instead of POST, as no changes are being made on the server. Additionally, don't forget to provide a name for the input.

<form action="/page" method="GET">

After submitting the form, the browser will direct to:

/page?name_of_input=what_the_user_entered

In your server code, retrieve the value using req.query.name_of_input and create a redirect response:

res.redirect(301, `/page/${encodeURIComponent(req.query.name_of_input)`)

Client-side

If you prefer a client-side approach, add an event listener to prevent the default behavior of the form and directly navigate to the desired URL by assigning it to location.

document.querySelector('form').addEventListener('submit', (event) => {
    event.preventDefault();
    location = `/page/${encodeURIComponent(document.querySelector('input').value)}`
});

Answer №2

Add the action to the /page and include the nickname within the name="" tag when sending it. To access the nickname, utilize req.params.nickname.

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

Activate the click event repeatedly in a loop

I am currently working on a bookmarklet to extract information from my Indiegala bundles that I have purchased. Instead of gifting the entire bundle, I prefer sending individual games one or two at a time as it is more convenient with the individual gift U ...

Executing a PHP script to initiate a ping transmission

I have a project to complete for my university involving the development of a simple application. However, I lack experience in this area and am unsure how to proceed. The objective is straightforward: I want to send ping requests to 50 IP addresses at t ...

Is there a way to prompt text typing actions to circumvent verification on an application?

As I explore ways to streamline my interactions on Whatsapp web, I am experimenting with a javascript shortcut. Specifically, I am creating predefined messages for quick responses to my contacts. To execute this task, I load the whatsapp page and inject jq ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

Guide on extracting the text from the <script> tag using python

I'm attempting to extract the script element content from a generic website using Selenium. <script>...</script> . url = 'https://unminify.com/' browser.get(url) elements = browser.find_elements_by_xpath('/html/body/script[ ...

Combine the serialized form data along with an array and post them together

I am encountering difficulties with sending the form through ajax. Along with the information input by the user, I also need to include an array of objects in the data being sent. AJAX POST: submitHandler: function (form) { $.ajax({ ...

Problems with the zoom functionality for images on canvas within Angular

Encountering a challenge with zooming in and out of an image displayed on canvas. The goal is to enable users to draw rectangles on the image, which is currently functioning well. However, implementing zoom functionality has presented the following issue: ...

Mastering Number Formatting in VueJS

While working with VueJS, I encountered difficulties in formatting numbers the way I wanted. After exploring options like the builtin currency filter and vue-numeric, I realized they required modifications to achieve the desired look. Furthermore, these so ...

Leveraging jQuery to extract a key-value pair and assign it to a new property by

I'm struggling with extracting a value from a key-value pair and inserting it into the rel property of an anchor tag. Even though I try to split the code and place the value correctly, it doesn't seem to work as expected. Instead of applying the ...

Preventing a user from accessing the login page if they are already logged in using Reactjs

I need assistance with implementing a "Login Logout" module in Reactjs using the nextjs framework. My goal is to redirect users to the "dashboard" page if they are logged in (email set in cookie). However, I am encountering an error with the following co ...

Transform seconds into an ISO 8601 duration using JavaScript

Dealing with ISO 8601 durations can be quite tricky. Efficiently converting seconds to durations is my current challenge, especially in JavaScript. Stay tuned for my solution and the Jest test script coming up next. ...

Optimize Material-UI input fields to occupy the entire toolbar

I'm having trouble getting the material-ui app bar example to work as I want. I've created a CodeSandbox example based on the Material-UI website. My Goal: My goal is to make the search field expand fully to the right side of the app bar, regar ...

Issue with the Styled Components Color Picker display

For the past 6 months, I have been using VSCode with React and Styled Components without any issues. However, recently I encountered a problem where the color picker would not show up when using CSS properties related to color. Usually, a quick reload or r ...

"Step-by-step guide on populating a select box with data from the scope

Hey everyone, I'm new to using Angular and hoping for some help with a simple question. I've created a form (simplified version below) that I want users to see a live preview as they fill it out. Everything was going smoothly with regular field ...

Accessing/Storing Pictures in MongoDB using Mongoose

I've been struggling with managing images in MongoDB for a while now. Everywhere I look suggests using GridFS because of the 16mb size limit per document. However, the documents I want to store are all <16mb this: var ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, { value: "CCT& ...

Alert: Route.get() is requesting a callback function, but is receiving an [object Undefined] while attempting multiple exports

I'm attempting to export the middleware function so that it can be called by other classes. I tried searching on Google, but couldn't find a solution that worked for my situation. Below is the code snippet: auth.js isLoggedIn = (req, res, nex ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Is there a way to grab code from a different HTML page using JavaScript and jQuery when the user clicks on something?

After testing various codes for the intended purpose mentioned in the title, I have observed a peculiar behavior. The code from settings.html appears briefly and then disappears rapidly. Javascript: function load() { $("#paste").load("settings.html") ...