首页 > 解决方案 > 如何访问 html 表单中的输入表单结果?

问题描述

我正在尝试将我的项目导入到 nodejs 应用程序中,我将能够在本地主机上运行该网站。这是可行的,因为当我运行 index.js 并输入 url 'http://localhost:8080/' 时,它会将我重定向到我网站的主页。

问题是,我的网站上有一个表单,我正在尝试访问该表单所在的 Feedback.html 页面。我要做的是在提交时返回表单数据,并将数据打印到终端(console.log())。如果您查看我的代码,我相信它是正确的。但是,我不确定我需要将我的 Project4 目录放在哪里。我应该把它放在我的视图文件夹中吗?

我对为什么需要视图文件夹感到困惑。另外,我的表单提交代码没有响应。

const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const { render } = require('pug');

const app = express();

//middleware and routing
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));

//Viewing website
app.use('/Project4', express.static('Project4'));
app.get('/', function(req, res){
    res.redirect('/Project4/index.htm');
});
//------------------------------

//***FORM SUBMISSION PART***
app.get('/Project4/Feedback.html', function(req, res){
    res.render('Project4/Feedback.html');
});
app.post('/submit-form', function(req, res){
    console.log(req.body);
    res.end();
});
//------------------------------

const PORT = process.env.PORT || 8080;

app.listen(PORT, function(error){
    if(error){
        console.log('Issue with server on port ' + PORT);
    }
    else{
        console.log('Server running on port ' + PORT);
    }
}); ```

[![This is what my app folder looks like. Where do I place the Project4 folder so that I can access its form via post method?][1]][1]


  [1]: https://i.stack.imgur.com/CzC8p.png

标签: javascripthtmlcssnode.jsexpress

解决方案


在您的表单中(也请包括表单),您要访问的事物的名称非常重要。使用名为body-parser的 npm 包(npm i body-parser然后执行此操作const bodyParser = require("body-parser")。这基本上只是提取传入请求流的整个正文部分并将其公开在 req.body 上。现在您已经设置了正文解析器,您只需要输入的名称(例如反馈)并执行此操作

console.log(req.body.feedback)

在 app.post 路线中。你应该准备好了!我应该提到的是表单应该有POST的方法,路线是正确的,按钮是一个提交按钮。这是我会做的。

表单 (HTML)

<form  action="/" method="post">
  <input type="text" name="feedback" placeholder="Your Feedback">
  <button type="submit">Submit feedback</button>
</form>

应用程序.js

const express = require('express');
const bodyParser = require("body-parser");
const app = express();
//Those were the modules
app.use(bodyParser.urlencoded({ extended: true }));
//use body parser with the urlencoded extended
app.get("/", function(req, res){
  res.sendFile(__dirname + "/index.html");
});
//sends the index.html when going to home route (/)
app.post("/", function(req, res){
  var feedback = req.body.feedback;
  console.log(feedback);
  res.redirect("/")
});
// when posted, we make a variable requesting the body, and then the name of the input, which is the name part of the input.
app.listen(3000, function(req, res){
  console.log("Server started on port 3000");
}); //self-explanatory.

最后一件事。需要您的 views 文件夹,因为您使用的是视图引擎。以EJS;如果我使用res.render(index, {feedbackstuff: feedback}),那么索引文件将需要是一个 .ejs 文件并位于 views 文件夹中。


推荐阅读