【问题标题】:Access HTML element from express js从 express js 访问 HTML 元素
【发布时间】:2019-04-15 12:31:03
【问题描述】:

我创建了示例应用程序,使用 express js 将文件上传到本地路径。

app.js

    const express = require("express");
    const app = express();
    const http = require("http").Server(app).listen(3000);
    const upload = require("express-fileupload");

    app.use(upload());

    console.log("Server Started");

    app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
    }
    )

    app.post("/", function (req, res) {
    if (req.files) {
        //console.log(req.files);
        const file = req.files.filename;
        const filename = file.name;

        file.mv("./upload/" + filename, function (err) {
        if (err) {
            console.log(err);
            res.send("error occured");
        }
        else {
            res.send("Done");
        }
        })
    }
    })

index.html

    <div>
    <h1 style="align-content: center">Upload your file here!</h1>
    </div>
    <div style=" background-color: white;
                padding:64px;
                display:flex;
                align-items:flex-start;
                justify-content: flex-start;
                box-shadow:  0 15px 30px 0 rgba(0, 0, 0, 0.11), 0 20px 15px 0 rgba(0, 0, 0, 0.08);
                box-sizing:border-box">

    <form label="upload" method="post" enctype="multipart/form-data" action="/">
        <label> Enter reference</label>
        <input type="text"></input>
        <br><br>
        <input type="file" name="filename">
        <input type="submit" value="upload">
    </form>
    </div>

我需要帮助才能访问 app.js 文件中输入 type = "text" 中输入的文本内容。任何帮助将不胜感激。

【问题讨论】:

  • NodeJS 是服务器端的,这意味着没有像客户端 javascript 那样可以访问的 html。如果您想访问存储在 dom 中的数据,您必须将其从客户端发送到服务器。
  • @CodeSpirit — 这就是 HTML 中的 &lt;form&gt; 所做的。
  • @Quentin - 就我而言,请告诉我如何访问 app.js 上的 type = "text"。

标签: html node.js express


【解决方案1】:

你有两个主要问题。

您没有发送数据

只有带有名称的表单控件才能成为成功的控件。 Something 必须等于输入的值。

给输入一个名字:

<input type="text" name="foo">

您不是在寻找数据

然后您正在使用的正文解析器(Busboy,包裹在 express-fileupload 中)将填充 req.body 对象,以便您可以通过 req.body.foo 访问它。

旁白

  • &lt;input&gt; 元素的结束标记在 HTML 中是禁止的。使用验证器:https://validator.nu/
  • 如果没有 for 属性或其中的表单控件,标签是无用的。见this guide

【讨论】:

    【解决方案2】:

    您必须为type=text 字段提供name 属性。然后您可以使用该名称访问该字段。假设您已将其设置为&lt;input type="text" name="user_input"&gt;&lt;/input&gt;。现在,您可以从您的app.postreq.body.user_input 的身份访问它。

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      • 2015-11-23
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多