Reputation: 73
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">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form class="test" action="http://localhost:8000/example" method="post">
<input type="submit" name="but" value="Press me">
</form>
</body>
</html>
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.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/example", (req, res) => {
console.log("pressed");
});
app.listen(8000, ()=>{
console.log("Running at 8000");
});
Upvotes: 0
Views: 381
Reputation: 61
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.
Upvotes: 1
Reputation: 21
Change this...
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
to this...
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
Upvotes: 1