Navigating to a different page with fresh data in Express.js

While browsing the homepage, I come across a list of names. Clicking on one of the names triggers a post request to the backend. At this point, my goal is twofold: firstly, fetch the corresponding profile data from the database; secondly, redirect to the profile page and showcase that particular data.

Upon conducting some research, it appears that setting up an http session variable and populating it with my profile data before directing to the profile page might be the most effective approach. Would you say this is the best way to handle the situation?

Here is my HTML structure:

<div class="result" onclick="loadProfile(this)" onmouseover="showActions(this)" onmouseleave="removeActions(this)"> 
     <p id="user-id" style="display:none;"> 123456 </p>
     <div class="person-info">
              
     </div>  
</div>

This is my front-end JavaScript function:

function loadProfile() {

}

How should I structure the get request? And how can I pass the ID as a parameter?

Answer №1

When querying data, it is important to use a GET request instead of a POST request. A POST request is typically used for adding or modifying records, while a GET request is meant for retrieving existing data. To construct a proper URL for querying data, you should format it like this:

/profile?id=someName

Once you have the URL set up, you can create a route handler on your server (or whatever name you prefer) that corresponds to the URL. This route handler will extract the value of "id" from the query string in the URL, which can be accessed using req.query.id if you are using request.

The extracted id value can then be used by the route handler to retrieve the relevant data from the database and display the corresponding profile page.

This process does not require a session or a redirect, making it stateless and more efficient from an HTTP server perspective. Additionally, by following this method, you create a URL structure that allows users to bookmark the profile page or share direct links in HTML.

If you need help switching from a POST to a GET request in your client-side code, please provide the HTML/code responsible for the current request, so we can offer more specific advice. If you are using an HTML form, you can configure it to generate a GET request with the data included in the query string.

In the function loadProfile(), you can simply construct the URL by fetching the ID value based on the clicked element and then redirecting to that URL like so:

let id = <code to get id from the current HTML, based on the click>
let newURL = `/profile?id=${id}`;
window.location = newURL;    // browser will navigate to the specified page

Ensure to set up the appropriate route on the server to handle this URL redirection effectively.

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

Managing dependencies with Yarn or npm

While experimenting with remix and mui v5, I encountered some issues. When using npm and running npm run dev, I received the following error: Error: Directory import '.../playground/remix-mui-dev/node_modules/@mui/material/styles' is not supporte ...

Updating model names and table names with Loopback and MySQL in Node.js can easily be done by following a few

Utilize Loopback(nodejs) in conjunction with mysql. I am looking to alter the model name and table name to something different. I prefer not to display the table name in the API URL. New table name = 'super_member' New model name = 'memb ...

Comparison between belongsTo and hasMany associations in Sequelize

Consider a scenario where we have a "shirt" table and a "john" table. When using Sequelize, if we define db.john.hasMany(db.shirt), a foreign key is created in the "shirt" table. Similarly, when we use db.shirt.belongsTo(db.john), a foreign key for "joh ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

Power Query M - Tackling Expression Error in Transforming Lists to Text

In my code, I'm using Web.Contents to make an API request. The access token I pass as a parameter is dynamically generated by a separate function. let Source = Json.Document( Web.Contents( {"https://api-url.com/endpoint/id"} ...

What is the process of importing node modules and referencing the exported name of a module?

Upon importing { createStore } from 'redux' in index.js, what exactly does 'redux' refer to? I attempted to search through the src directory of the redux package within the node_modules folder but was unable to locate any export named & ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

Using Express.js to import a SQL file

I am facing challenges while attempting to import an sql file into Express JS. I have tried various codes involving the mssql and fs modules, but none seem to be working as expected. fs.readFile(__dirname +'/database.sql', function (err, sqlFile ...

Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions? const got = require("got") class PriceCheck { constructor() { ...

No matter the way I input the URL in the AJAX call, the response always comes back as successful

I ran into an issue with my ajax request. It was supposed to be a GET request that returned some data, but no matter how I configured the URL, it always gave a success response even when it didn't actually succeed. var id = 5; $.ajax({ type: ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

The MongoDB array is not successfully receiving file data (images, PDFs)

Each time I upload a new file using postman, it replaces the existing file and keeps only the newly uploaded file saved. I attempted to use the document.push method but encountered an error message saying "TypeError: documents.push is not a function". How ...

Tips for crafting effective error messages to communicate with users

One of the biggest challenges I face is crafting clear error messages for clients in case of errors. A typical scenario involves using Axios and a third-party API to fetch data, requiring appropriate error handling for both. Axios' error handling doc ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

Error in Moongose: Using .populate on a key with whitespace is not functioning as expected

I am currently working with Express and Mongoose for database operations. I have encountered an issue where attempting to populate a path with a key that contains a whitespace causes it to be ignored. MongoDB Model: const OrgCrimeSchema = new Schema({ g ...

Express Node can execute a Model method across a collection

Here’s my question: var query = postModel.find({ //etc }); query.exec(function(err, posts) { }); Now, I also have a Model method: PostSchema.method('deepPopulate', function(cb) { //stuff }); I can use it in other finds like this: post.de ...

Webpack encountered an error: SyntaxError due to an unexpected token {

I recently implemented Webpack for my Django and Vue project, but I encountered an error when trying to run webpack. Can anyone help me troubleshoot this issue? $ node --use_strict ./node_modules/.bin/webpack --config webpack.config.js node_modules/webp ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

Callback for Fs.writeFile not being executed

Currently running on Node version 8.11.2 A fairly simple CSV export feature has been implemented. This function receives an array of objects and dynamically creates the file headers based on the properties of these objects. const csvExport = (dataList, f ...

Tips for showcasing checkbox options on an HTML page (utilizing ejs) following the retrieval of information from MongoDB and making it editable for the User

Currently, I store data in mongo for a multiple-choice question and indicate the correct answers. In mongo, I save them like this: question.options.option1.check = "on" for the correct answers. When I navigate to the "edit" page, I retrieve the specific ...