发送错误消息并在

发送错误消息并在

本文介绍了发送错误消息并在 Express.js 中重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习 Express.js.我有以下简单的 HTML 表单:

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>

用户应该输入两个数字,然后将它们的和返回给他们.简单的 Express 服务器就在这里.body-parser 包含在 node_modulesused 中,由 Express app 用于操作 req 对象并提取表单数据.

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 used 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;
}

我有兴趣将用户重定向到 POST 中间件中的 index.html 以便他们可以在不刷新 URL 的情况下再次使用计算器,无论他们是否使用成功或不.由于这是在后端,我无法访问 window 对象,也无法直接使用它.不知道如何做到这一点.有什么想法吗?

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?

推荐答案

在 express 中重定向:

To redirect in express:

res.redirect('/');

这并不完全类似于 window.location,但它确实重定向.

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.

解决问题的更好方法是使用 AJAX(提交表单而不重新加载页面);查看这个 jQuery 示例(显然是客户端):

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
      }
   });
}

此外,您可以使用提供的变量 __dirname 作为绝对路径.

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

这篇关于发送错误消息并在 Express.js 中重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:03