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

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

Efficiently sending data to Service Bus from an HTTP-triggered function

How can I link the output to service bus? I've configured an out binding in my Azure function: { "queueName": "testqueue", "connection": "MyServiceBusConnection", "name": "myQueueItem", "type": "serviceBus", "direction": "out" } I started ...

Using the getAttribute method in Edge with JavaScript

My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get propert ...

Angular filter is designed to search for elements that contain a specific value, rather than only those that are an exact match

I am currently trying to relate rules to fields using the 'filter' filter in Angular. You can see an example of this implementation here: http://plnkr.co/edit/dQiv5lRzhQNjXZ6pVdWO?p=preview The code I am using for this purpose is as follows: &l ...

Modular REST architecture in Express.js

My plan is to create a solely REST API using Express.js, and in my search for boilerplate projects, I found that none of them offer the level of modularity I desire. By modularity, I mean having all code related to a specific module, such as articles, cont ...

Animating transitions on a dynamic Bootstrap navbar using jQuery

I have the code attached here, and I successfully changed the color of the navbar and logo when scrolling down. However, I am looking to add a transition effect when this change occurs. I experimented with various transition options in CSS, but unfortunat ...

Utilizing Vue.js to pass a slot to a customized Bootstrap-Vue Table component

I am currently in the process of developing a wrapper for the bootstrap-vue Table component. This particular component utilizes slots to specify cell templates, similar to the following example: <b-table :items="itemsProvider" v-bind="options"> ...

Using Node.js and the Azure DevOps Node API, you can easily retrieve attachments from Azure DevOps work items

Encountering a problem while attempting to download an attachment for a work item in Azure DevOps. Utilizing the node.js 'azure-devops-node-api' client (https://www.npmjs.com/package/azure-devops-node-api) to communicate with ADO API. Retrieving ...

Tips on retrieving a specified string from within an array of strings

I need help extracting the inner string from this array within a string: '["sgrdalal21"]' Can someone provide guidance on how to accomplish this? ...

Guide to creating standalone Express middleware that can interact with the raw request body

Can anyone help me with writing an Express middleware that can access the raw request body without affecting other handlers or middlewares? I want to achieve something like this: const middleware = [ express.raw({ type: '*/*' }), (req, res, n ...

Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement. For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be ...

Is there a way to create a JavaScript function that relies on a successful form submission?

After attempting to modify a post on Stack Overflow, I am facing issues with my JavaScript code. As a beginner, it's possible that I overlooked something in the code causing it not to work as expected. The project I'm working on involves creatin ...

Is there a way to gather information from a web service and neatly display it within an HTML table?

Is it possible to fetch a JSON array from a web service and save it in a variable? Consider the following table structure: <table id="myTable" border="1"></table> The table is populated using the code below: // JSON array var myData = metho ...

Is there a way for me to connect my client port to my express server port for listening purposes?

I am currently in the process of developing a chat application using Redux, Express, and Socket.io. While I have successfully set up Express and Socket.io, I am facing an issue connecting the server to the front-end react/redux application. At present, my ...

What is the best way to retrieve a specific number of documents from MongoDB?

I am currently facing an issue with my code that is returning all news related to a company. However, I only want the first 15 elements. Is there a way to achieve this? The following code snippet retrieves all news for a company using the google-news-jso ...

A guide on utilizing Socket.io to efficiently transfer data to a specific client within a designated chat room

Can someone please advise on the correct way to send data to a specific client in a specific room using socket io? The code snippet I have been trying is: I am using the following command: socket.to(socket.id).emit('change', {data}) However, i ...

What is the process for accessing data of signed-in users?

I currently have a mobile app developed using the MERN stack that utilizes passportjs for user authentication and login (linked to a mongodb database via axios). However, I am facing an issue where I cannot associate the data/log entered by the user with t ...

What is the best way to change the folder name when hovering over it?

Typically, my website displays categories with images from the /thumb-min/ directory. For example, 95-IMG_6509.JPG is loaded like this: /thumb-min/95-IMG_6509.JPG When I navigate to the details page, it loads the image from: /thumb-medium/95-IMG_6509.JP ...

What is the best way to terminate a MongoDB client connection in the event of an error?

I am currently managing a configuration where I have set up a MongoDB instance and operating two JavaScript services on a Linux server. One of the services, moscaService.js, is responsible for listening to MQTT topics on the server and storing the incoming ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...