简体   繁体   中英

Send error message and re-direct in Express.js

Learning Express.js. I have the following simple HTML form:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calculator</title>
  </head>
  <body>
    <h1>Calculator</h1>
    <form action="/" method="post">
      <input type="text" name="num1" placeholder = "First Number" value=""> <br>
      <input type="text" name="num2" placeholder = "Second Number" value=""> <br>
      <button type="submit" name="submit">Calculate</button>
    </form>
  </body>
</html>

The user is supposed to input two numbers, and their sum is returned to them. The simple Express server is here. body-parser is included in node_modules and use d by the Express app in order to manipulate the req object and extract the form data.

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

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

app.listen(3000, () => {
  console.log("Server spun on port 3000.")
});

app.get("/", (req, res) => {
  console.log("Serving a GET request at root route.");
  res.sendFile(absoluteDirPath() + "index.html");
});

app.post("/", (req, res) => {
  console.log("Serving a POST request at root route.");
  let num1 = Number(req.body.num1);
  let num2 = Number(req.body.num2);
  if(isNaN(num1) || isNaN(num2)) {
     res.send("<p>Need numerical values.</p>"); 
   } else {
    res.send("<h3>Result: " + (num1 + num2) + "</h3>");
  }
  // How can I re-direct the user here? 
});

function absoluteDirPath() {
  const path = require('path');
  return __dirname + path.sep;
}

I am interested in redirecting the user to index.html in the POST middleware so that they can use the calculator again without refreshing the URL, whether they used it successfully or not. Since this is in the backend, I don't have access to the window object and I can't play around with it directly. Not sure how this could be done. Any ideas?

To redirect in express:

res.redirect('/');

This doesn't exactly similate window.location , but it does redirect.

However, I don't see why you should redirect, because you are sending the client a message, and before they get to see it you already redirected them.

A better way to approach your problem would be to use AJAX (submitting a form without reloading the page); check out this jQuery example (client-side obviously):

function submitFormWithoutReloading() {
   $.ajax({
      type: "POST",
      url: "/",
      data: {
         num1: $('#idOfYourFirstInput').val(),
         num2: $('#idOfYourSecondInput').val()
      },
      success: function(res) {
         alert(res); // This is what the server returns
      }
   });
}

Also, you can just use the provided variable __dirname for the absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM