[英]Send error message and re-direct in Express.js
Learning Express.js.学习 Express.js。 I have the following simple HTML form:我有以下简单的 HTML 表格:
<!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.简单的 Express 服务器在这里。 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. body-parser
包含在node_modules
中,Express app
use
d 来操作req
object 并提取表单数据。
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.我有兴趣将用户重定向到POST
中间件中的index.html
以便他们可以再次使用计算器而无需刷新 URL,无论他们是否成功使用它。 Since this is in the backend, I don't have access to the window
object and I can't play around with it directly.由于这是在后端,我无法访问window
object 并且我无法直接使用它。 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.这并不完全类似于window.location
,但它确实重定向。
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);解决问题的更好方法是使用 AJAX (提交表单而不重新加载页面); check out this jQuery example (client-side obviously):查看此 jQuery 示例(显然是客户端):
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.此外,您可以只使用提供的变量__dirname
作为绝对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.