Reputation: 17
Having an issue with processing post request in node.js and it is showing the error: Cannot POST /index.html Since body-parser is deprecated, I am stuck with this error
const express = require("express");
const app = express();
app.use(express.json({ limit: '50mb' }));
app.get("/", function(req, res){
res.sendFile(__dirname+"/index.html");
});
app.post("/", function(req, res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1+num2;
res.send(String(result));
});
app.listen(3000, function(){
console.log("Server is running on port 3000");
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Calculator</h1>
<form action="index.html" method="post">
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<button type="submit" name="submit">Calculate</button>
</form>
</body>
</html>
Upvotes: 0
Views: 76
Reputation: 1156
I don't get it. What is your requirement with these code snippets?
Since body-parser is deprecated, I am stuck with this error
body-parser
is now part of Express and you can just get it by writing,
app.use(express.urlencoded({ extended: false }));
error: Cannot POST /index.html
The reason Express throw this error is because, you don't have matching POST route. Instead you have POST /
route. I would suggest you to update the <form>
's action to /
instead of index.html
.
<form action="/" method="post">
<input type="text" name="num1" placeholder="First Number" />
<input type="text" name="num2" placeholder="Second Number" />
<button type="submit" name="submit">Calculate</button>
</form>
Upvotes: 1