Solution 1 :

It’s occurs because app.use () is treated as middleware for your application. To work properly you should use app.get (). Here is more detailed explanation. Other alternative is provide your html as an static content, you can see more about here.

To work properly you should change your code to this:

app.get("/", (req, res) => {
  res.sendFile(__ dirname + "/index.html");

You can also modify your HTML to this:

<form class="test" action="/example" method="post">

Because is in the same host. You just use complete url when performing action to other host.

Solution 2 :

Change this…

app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");

to this…

app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");

Problem :

I have recently started picking up Node.js with the Express framework. I created a simple server and attached an HTML file with a form consisted of a single button of type submit which was supposed to send a post request to the server. It doesn’t give me any errors but when I try to log a message to the console upon pressing the submit button, nothing happens. I am pretty sure it has something to do with the HTML form syntax but I can never be too sure. Here is the HTML:

<html lang="en" dir="ltr">
   <meta charset="utf-8">
  <form class="test" action="http://localhost:8000/example" method="post">
    <input type="submit" name="but" value="Press me">

Here is the Express code:

const http = require("http");
const app = require("express")();
const path = require('path');
const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: true })); 

app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});"/example", (req, res) => {

app.listen(8000, ()=>{
console.log("Running at 8000");


Comment posted by Ameer


Comment posted by Пламен Цанев

Can I somehow make it not transfer me to another page f. e. the /example, its only there because I thought it would fix the issue but it didn’t, I’d like to keep the current page. And also how did that solve my problem?


Leave a Reply

Your email address will not be published. Required fields are marked *