How can we showcase an HTML file in Express by utilizing a POST request?

My objective is to successfully submit my form data and then dynamically navigate to an HTML file where the values are displayed. Here's the code snippet from my app.post function in Express:

 const results = fs.readFile("order.html", "utf-8", (err, data) => {
    let output = data.replace("{%foodTotal%}", response.data.order_value);
    console.log("output", output);
  });

  res.send(results);

Upon submitting the input form data, this code will log all the data in the console.

This is what the console in my terminal will show:

output
    <body>
        <h1>Thank you for buying!</h1>
        <p>Here are your details</p>
        <p>Food Total: $100.00</p>
    </body>

However, I am struggling to figure out how to display this console.log() data on my browser. My goal is to showcase the contents of 'order.html' after form submission, highlighting the updated values.

Below is a preview of the 'order.html' File I want to display post-form submission:

<body>
    <h1>Thank you for buying!</h1>
    <p>Here are your details</p>
    <p>Food Total: {%foodTotal%}</p>
</body>

In addition, here is the app.get function in my Express file:

app.get("/order", (req, res) => {
  res.sendFile(path.join(__dirname, "order.html"));
});

If I attempt to change res.send() to res.redirect('order'), it will only display the HTML normally without the updated form values. How can I achieve displaying the HTML file with the updated values in the browser upon form submission?

My desired outcome is to submit the form data and have the 'order.html' file display in the browser with the data included, similar to the following:

<body>
    <h1>Thank you for buying!</h1>
    <p>Here are your details</p>
    <p>Food Total: $100.00</p>
</body>

Is this achievable with regular HTML files or would I need to utilize something like EJS? Previously, I hardcoded the HTML in my express.js file, but that doesn't seem like the optimal solution.

Answer №1

To ensure efficiency and organization, incorporating a form of templating is crucial.

A solution mentioned in response to a related query discusses the implementation of a custom templating engine that would be suitable for straightforward scenarios like the one you have described.

As your project evolves and becomes more complex, it may be wise to consider integrating a templating engine.

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

What is the process of dynamically loading CSS into an HTML document?

In my C# program, I am utilizing a web browser control and setting its HTML property programmatically by loading it from an HTML string variable. While this setup works almost perfectly, I have noticed that it loses the reference to the CSS file. I believe ...

The state value is not preserved after redirecting to another page

For the past couple of days, I've been struggling with an issue and I can't seem to figure out what I'm doing wrong. My goal is to create a login page that redirects users to the dashboard after they log in. To maintain consistency acros ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

Interactive map navigation feature using React.js

Can someone help me figure out how to create a dynamic map with directions/routes? I am currently using the Directions Renderer plugin, but it only shows a static example. I want to generate a route based on user input. Below is the code snippet: /* ...

Implementing Material-UI Autocomplete: How to Include a Starting Value for the startAdornment

I am using autocomplete with multiple selection permission. https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js In the provided example, there are 3 options for cities. How can I manually insert a value in TextField that is automatically selected ...

The req.isAuthenticated function isn't functioning as expected

I have been working on a nodejs express application and I am trying to implement authentication using passport local strategy with email and password. However, after successful login, when I check the req.Authentication() function, it returns false. Can so ...

How can I retrieve and store session information during the authorization event in Socket.io with express-sessions?

I have set up a websocket using Socket.io and the express 4 framework on a node.js server. Currently, I am working on implementing an authorization step for my users when they are using the websocket. Upon a user connection, a token is passed as a query ...

Avoid retrieving data during the fetching process

I have been working on an application that utilizes Redux for state management. Furthermore, I have been using the native fetch method to fetch data. return fetch("https://dog.ceo/api/breeds/image/random").then(res => res.json()); Within my React co ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

Ways to update HTML content generated by Ajax

Having some difficulties modifying the HTML content generated by AJAX. This is the code snippet from the page: @model IEnumerable<WE_SRW_PeerNissen.Models.Reservations> @{ ViewBag.Title = "List"; Layout = "~/Views/Shared/_Layout.cshtml"; } ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

The drawbacks of using toJS() in React Redux: Is it really necessary in mapStateToProps()?

After reading through the Redux documentation, I came across a recommendation to not use Immutable with Redux. This advice has left me feeling confused. Why should I avoid using toJS() in the mapStateToProps function? It seems that React already uses Dee ...

How can you apply a class to a different element by hovering over one element?

Is there a way to darken the rest of the page when a user hovers over the menu bar on my website? I've been playing around with jQuery but can't seem to get it right. Any suggestions? I'm looking to add a class '.darken' to #conte ...

How can I sync the data from my local mongodb installation with a remote mongodb server or cluster?

In order to establish a connection with a specific MongoDB database locally, I utilized this code snippet. const express = require('express'); const mongoose = require('mongoose'); const app = express(); const connect ...

Troubleshooting Parallax Logic in NextJS

import Head from 'next/head' import styles from '../styles/Home.module.css' import Image from 'next/image' import React, { useRef ,useEffect, useState } from 'react'; export default function Home() { let ref = use ...

Using factories in controllers does not function properly in Angular 1.6

My head is spinning with this one. There are 3 files in play: app.js, app.services.provider.js, admin.js In app.js, I set up my module: (function() { angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { ...

What is the best way to close an ajax page within the main page using a button?

I am dealing with a situation where I have 2 pages. The first page contains a div called 'ajaxicall', which loads another page inside it. The challenge I am facing is figuring out how to close the second page when I click on the "close" button w ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

Node.js encountering issues with multiple concurrent connections to SQL servers in mssql due to interference between them

I am currently utilizing mssql in my Node.js express application to establish connections with multiple databases on various SQL servers. To illustrate the basic structure of my code, I have created the following example: app.get('/api/example') ...

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...