Loading...

Access HTML element from express js


I've created the sample app using express js to upload the file on the local path.

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>

I need the help to access the text content entered on the input type = "text" from the app.js file. Any help would be appreciated.

- - Source

Answers

answered 1 week ago Al Amin #1

You have to give a name attribute to the type=text field. Then you can access the field using the name. Suppose you have set it as <input type="text" name="user_input"></input>. Now from your app.post you can access it as req.body.user_input.

answered 1 week ago Quentin #2

You have two major problems.

You aren't sending the data

Only form controls with names can be successful controls. Something has to equal the value typed in.

Give the input a name:

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

You aren't looking for the data

Then the body parser you are using (Busboy, wrapped in express-fileupload) will populate the req.body object so you can access it via req.body.foo.

Asides

  • The end tag for <input> elements is forbidden in HTML. Use a validator: https://validator.nu/
  • Without a for attribute or a form control inside it, a label is useless. See this guide

comments powered by Disqus