Serve static files using ExpressJS when a post request is made

My Express server is set up to serve static files for my website and it's working fine:

var express = require('express');
var app = express();
var path = require('path');
var p = path.join(__dirname, '../web/public');
app.use("/files", function (req, res) {
    return res.send("I will do something on server");
});
app.use(express.static(p));
app.use('/*',express.static(p));
let port = 80;
var server = app.listen(port);

However, I'm encountering an issue with form submissions causing a redirect which results in a message like this:

Cannot POST /dashboard/

I've tried adding the following before declaring the port:

app.post(express.static(p));
app.post('/*', express.static(p));

But it doesn't seem to fix the problem.

I want all requests to be served from index.html since it contains all the app logic. To achieve this, I have included the following code:

app.use(express.static(p));
app.use('/*',express.static(p));

How can I ensure that post requests redirect to index.html? My goal is to provide users with the option to save their login information securely while also using POST for sensitive data transfer.

If you have any suggestions or ideas on how to solve this issue, I would greatly appreciate it! Thank you!

Answer №1

There isn't a file named dashboard, which means that there is nothing for express.static to serve.

To address the dashboard route, you can follow these steps:

app.post("/dashboard", function (req, res) {
  return res.send("I will take action on this post");
});

If you wish to redirect 404 traffic to index.html, you can accomplish this after defining all your routes:

app.use("/", function (req, res) {
  return res.redirect("/index.html");
});

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

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

Sending a POST request to an ExpressJS route functions well in a local environment, but encounters an HTTP 405 error when

Within my React application, I am making requests to my backend Node/Express app using axios. In my development environment, everything functions properly when I utilize a function like this: await axios.post('/createproduct', createProductBody) ...

What could be causing the issue with AJAX not running in a Python Django deployment on Heroku

My Django application is successfully deployed on Heroku, but I'm facing an issue with executing Ajax in the template. The Ajax functionality works perfectly fine on my local machine, however, it's not working on Heroku. I've included a snip ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

The npm installation is encountering issues on Windows at the moment

Everything was running smoothly on my Mac, but when I tried the same process on Windows, the npm install crashed. Here's the error message I encountered: Despite attempting various solutions from Stack Overflow and multiple Google searches, including ...

The MySQL error wreaks havoc on the Node.js server, causing it to

Whenever there is an error or exception coming from MySQL, my nodejs server ends up crashing. This is the code snippet from my backend where I tried using if-else in the query function to handle the response, but it still crashes the server. Even with try ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

Determining if a div is scrolled to the bottom in ASP.NET

Seeking help as I am unsure how to tackle this task. My project involves using asp.net, where I have a div that has overflow:auto enabled to display terms and agreements. Additionally, there is an asp.net checkbox control with visibility set to "false". ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

The special function fails to execute within an "if" condition

As a newcomer to JavaScript/jQuery and Stack Overflow, I kindly ask for your patience in case there are any major errors in my approach. I am currently developing an HTML page with Bootstrap 3.3.7, featuring a pagination button group that toggles the visib ...

What is the best way to assign a URL to an image source using a JavaScript variable?

I am working on a script that displays different image URLs based on the time of day using an if-else statement. I want to dynamically load these images in an img src tag so that a different picture is loaded for each time of day. I have defined variables ...

Using the div id within JavaScript to create a new Google Maps latitude and longitude

Here is my code for locating an IP using Google Maps. I am trying to set new google.maps.LatLng('< HERE >') to <div id="loc"></div>. How can I achieve this where the result will be 40.4652,-74.2307 as part of #loc? <scrip ...

I created a thorough duplicate that successfully addressed an issue with a table

Currently, I am facing an issue with the material-table library as it automatically adds a new element called tableData to my object when I update it using Patch in my code and API. To resolve this problem, I tried implementing both a conventional and cust ...

Transform all Date fields in the Array to a standardized date format

I have an array with various fields, including a field called dateofbirth. I need to remove the time and change the format to MM-DD-YYYY. var records = [ { "recordno":"000001", "firstname":"Bo", "middlename":"G", "lastn ...

What is the mechanism behind image pasting in Firefox's imgur integration?

Start by launching an image editing software and make a copy of any desired image. Avoid copying directly from a web browser as I will explain the reason later on. Navigate to "http://imgur.com" using Firefox. To paste the copied image, simply press Ctrl+V ...

The lack of synchronization between the updated state in one function and its counterpart is causing discrepancies, resulting in the incorrect information being sent to the API

Whenever I press the following button: <Button onClick={(e) => { addToCard(item); handleprisma(); }} > add to cart </Button> This function is meant to add the item to my shopping cart: const addToCard = (item) => { co ...

The file was mistakenly interpreted as a document but was actually transferred with the MIME type text/csv from "http://localhost:3000/post"

Attempting to initiate a download of the file. res.attachment('./public/uploads/name-1540993539785.csv') The file is downloaded, however its content only shows "uploads/name-1540995323357.csv" instead of the actual data. An error message appe ...

Colorful radial spinner bar

I am interested in replicating the effect seen in this video: My goal is to create a spinner with text in the center that changes color, and when the color bar reaches 100%, trigger a specific event. I believe using a plugin would make this task simpler, ...

Can you explain the relationship between HTML 5 Canvas coordinates and browser pixels?

When trying to use HTML 5 canvas as a drawing board in my application, I encountered an issue. The drawings appear at an offset from the mouse pointer. My method involves using the Jquery .offset function to determine the event's position on the canv ...

Sequential execution of multiple useState updates when an update triggers a re-render

Can you explain why the function setPeople is being executed after setFirstName, setEmail, and after the event handler has been exited? const [firstName, setFirstName] = useState(''); const [email, setEmail] = useState(''); const [peopl ...