【问题标题】:How do I open a page when a submit button is pressed in Express?在 Express 中按下提交按钮时如何打开页面?
【发布时间】:2017-09-08 14:27:35
【问题描述】:

我说的不是 Button 标签。我说的是提交类型的输入标签。我正在使用 fs 加载我当前的页面。我正在努力学习表达。

Server.js:

var express = require('express');
var path = require('path');
var fs = require('fs');

var app = express();

app.use(express.static(path.join(__dirname+'/public/')));
app.use(require('body-parser').urlencoded({ extended: true }));

app.get('/', function(a,b,c){
  fs.readFileSync('index.html');
});

app.post('/testaction', function(a,b){
    console.log(a.body.log);
    fs.readFileSync('public/Logged.html');
});

app.listen(3000);

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page</title>
  </head>
  <body>
     <form method="post" action="http://localhost:3000/testaction">
       <h1>Log This:</h1>
       <input type="text" name="log"/>
       <input type="submit", value="Press Me!"/>
     </form>
  </body>
</html>

【问题讨论】:

  • 你能分享一些代码来帮助你弄清楚你想要做什么吗?听起来您正试图在客户端提交表单时将特定的静态页面发送回客户端,以响应特定的 POST 请求。

标签: html node.js forms express submit


【解决方案1】:

这里基本上不需要 fs。

例如 app.get() 有 2 个参数:您要处理的 url 和带有 2 或 3 个参数的回调。

通常我们这样使用它:app.get("/",(req,res)=&gt;{});(req = 请求,而 res = 响应)。

response 有发送文件的方法:http://expressjs.com/fr/4x/api.html#res.sendFile

现在对于您的问题,您可以将其作为 ajax 请求进行管理:

  • 在 index.html 中向/testaction 发出 POST ajax 请求。
  • 在 server.js 中只需在您的app.post 中返回一个状态
  • 创建另一个路由,例如app.get("/test",(req,res)=&gt;{res.sendFile("public/Logged.html");});
  • 如果您的 ajax 响应中的状态正常,则在 index.html 中重定向到 /test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 2023-03-09
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2019-03-05
    相关资源
    最近更新 更多