Sai Krishnadas
Sai Krishnadas

Reputation: 3409

Error shows when trying send request as form data

This is a simple calculator that can add numbers. The html form loads correct to the browser but then once I submit the form, I get a 404 error code

Error code : Cannot POST /index.html

index.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calculator</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>

calculator.js :

//jshint esversion:6

const express = require('express');
const bodyParser = require('body-parser');

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

//sending response
app.get("/",function(req, res){
  res.sendFile(__dirname + "/index.html");
});

//post
app.post("/",function(req,res){

  var num1 = Number(req.body.num1);
  var num2 = Number(req.body.num2);
  var result = num1 + num2;

  res.send("The result is: "+result);
});

//listen to port 3000
app.listen(3000, function(){
  console.log("Server listening on port 3000");
});

Upvotes: 0

Views: 38

Answers (1)

Erik CF
Erik CF

Reputation: 61

In your express server you are expecting the post calls to / and you are telling the form that has to send the form-data to index.html.

That means your form will be sending data to http://localhost:3000/index.html instead of http://localhost:3000/.

You should change action="index.html" to action="/".

Upvotes: 1

Related Questions