2

I'm trying to get data from HTML to my node.js sever to work with it.

I'm trying to make an email checker site, so I need to get data from input field (email to check), check it with REGEX if it has a correct syntax, then send back to html a response text. But I can't get the text from the input field in any way.

This is my code:

HTML FILE:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Email Verify</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!--===============================================================================================-->
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <!--===============================================================================================-->

</head>

<body>

    <div class="container-contact100">

        <div class="wrap-contact100">
            <form class="contact100-form validate-form"></form>
            <span class="contact100-form-title">
                Enter Email To Verify
            </span>

            <form action="/email" method="POST">
                <div class="wrap-input100" data-validate="Please enter email: example@domain.com">
                    <input class="input100" type="text" name="email" placeholder="E-mail">
                    <span class="focus-input100"></span>
                </div>

                <div class="container-contact100-form-btn">
                    <button class="contact100-form-btn" type="submit">
                        <span>
                            <i class="fa fa-paper-plane-o m-r-6" aria-hidden="true"></i>
                            Check
                        </span>
                    </button>
                </div>
            </form>
        </div>
    </div>

</body>

</html>

server.js

const mongoose = require('mongoose');
const dotenv = require('dotenv');
const app = require('./app.js');

dotenv.config({
    path: './config.env',
});

mongoose
    .connect('mongodb://localhost:27017/checker', {
        //'mongodb://localhost:27017/checker'
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
    })
    .then(() => {
        console.log('DB connection successful!');
    });

const port = process.env.PORT || 3000;

app.listen(port, () => {
    console.log(`App running on port ${port}...`);
});

and my Express app.js

const express = require('express');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');


const serverRoute = require('./routes/serverRoute.js');


const app = express();

//app.use(express.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(morgan('dev'));


const indexView = fs.readFileSync(`${__dirname}/view/index.html`, 'utf-8');

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    next();
});

app.use(express.static('view'));

//app.use('/api', serverRoute);

app.use('/', (req, res) => {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    res.end(indexView);
});

var emailVar;

app.post('/email', (req, res) => {

    emailVar = req.body.email;

    console.log(emailVar);

    res.send('You sent the name "' + req.body.email + '".');
});

app.use(express.static(path.join(__dirname, 'view/index.html')));


module.exports = app;

As I can see in this screen, the POST should be made, but I can't get the data to work with it in Node.js in any way.

Any ideas?

  • I believe to parse the data received from the frontend you need a [body-parser](https://www.npmjs.com/package/body-parser). Please install body-parser dependency, import it and use it using express middleware `app.use`. Also, after express 4 `express.json` has been depreciated. Please have a look [here](https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4) – mkamranhamid Sep 15 '20 at 14:09
  • Still getting the same - nothing. Is there an error in my code logic? I also edited the first post with body-parser added – Bogdan Doncea Sep 15 '20 at 14:18
  • Ah! gotcha. You're sending formdata and receiving json – mkamranhamid Sep 15 '20 at 14:20
  • So app.post(...) is not getting the email field from my JSON using req.body.email? It should – Bogdan Doncea Sep 15 '20 at 14:22
  • 1
    You either need to change the data that has been sent from frontend to `json` or receive the formdata on backend. But to receive the formdata you'll have to install another module which I dont prefer. Can you have a look at this [article](https://www.w3.org/TR/html-json-forms/) and [this](https://www.learnwithjason.dev/blog/get-form-values-as-json/) – mkamranhamid Sep 15 '20 at 14:25
  • @mkamranhamid enctype='application/json' this solved my issue. Thank you, sir – Bogdan Doncea Sep 15 '20 at 18:28
  • Please mark this ticket as solved – mkamranhamid Sep 16 '20 at 07:57

0 Answers0