Languages
[Edit]
EN

Express.js - send form to node server

0 points
Created by:
Dollie-Rutledge
806

In this article, we would like to show you how to send the form from node server in Express.js.

To send the form from the node server using Express.js, we use the sendFile method on the response object.

Practical example

Project structure: 

/C/
 |
 +- Project/
     |
     +-- loginForm.html
     |    
     +-- server.js

server.js

const express = require('express');

const app = express();

app.get('/', (request, response) => {
    const pathToFile = __dirname + '/loginForm.html'
    response.sendFile(pathToFile);
});

app.post('/auth', (request, response) => {
    const username = request.body.username;
    const password = request.body.password;
    // authentication 
    if (isCorrect) {
        response.send('Success')
    } else {
        response.send('Incorrect Username and/or Password!');
    }
}

app.listen(3000, () => {
  console.log(`server is listening at http://localhost:3000`);
});

loginForm.html

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
    <div>
        <h1>Login Form</h1>
        <form action="/auth" method="POST">
            <input
                type="text"
                name="username"
                placeholder="Username"
                required
            />
            <input
                type="password"
                name="password"
                placeholder="Password"
                required
            />
            <input type="submit" />
        </form>
    </div>
</body>
</html>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join