nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.48k stars 284 forks source link

Issue with Form Submission #4100

Closed gryllifish closed 6 months ago

gryllifish commented 1 year ago

Details

I am experiencing an issue with submitting a form on my website. When I fill out the form and click the submit button, nothing happens and I do not see any network requests in the browser console.

The form is supposed to submit to the URL https://example.com/, but it seems that the form is not able to send a POST request to this URL.

I have checked the JavaScript console and there are no error messages, and I have also verified that the form fields have the correct names and that the submit button has the correct type.

I am using a shared hosting plan with PHP 7.3.33, and my website was built with WordPress. Recently, I decided to change the design of my website and I did it with Node.js v18.14.0.

I followed the advice of technical support, and I deployed the app to the server. using the application manager.

Now, the technical support answered me this: "What I can confirm is that it's making a successful POST request to "/" (e.g the same page), however there are no errors".

This is my form html:

<form method="post" action="/" id="form">
                        <div class="row gtr-uniform">
                            <div class="col-6 col-12-xsmall"><input type="text" name="name" id="name" placeholder="Nombre" /></div>
                            <div class="col-6 col-12-xsmall"><input type="email" name="email" id="email" placeholder="Email" /></div>
                            <div class="col-12">
                                <select id="type" name="type">
                                    <option value="" selected>Selecciona Tipo</option>
                                  </select>
                            </div>
                            <div class="col-12">
                                <select id="make" name="make" disabled>
                                    <option value="" selected>Selecciona Marca</option>
                                  </select>
                            </div>
                            <div class="col-12">
                                <select id="model" name="model" disabled>
                                    <option value="" selected>Selecciona Modelo</option>
                                  </select>
                            </div>
                            <div class="col-12">
                                <select id="year" name="year" disabled>
                                    <option value="" selected>Selecciona Año</option>
                                  </select>
                            </div>
                            <div class="col-12"><textarea name="message" id="message" placeholder="Tu mensaje" rows="4"></textarea></div>
                            <div class="col-12">
                                <ul class="actions special">
                                    <li><input type="submit" value="Enviar" class="primary" /></li>
                                </ul>
                                <div id="spinner" style="display: none;">
                                <svg class="spinner" width="65px" height="65px" viewBox="0 0 66 66" xmlns="http://www.w3.org/2000/svg">
                                    <circle class="path" fill="none" stroke-width="6" stroke-linecap="round" cx="33" cy="33" r="30"></circle>
                                 </svg></div>
                                <span id="form-message" style="display: none;">Consulta enviada con éxito</span>
                            </div>
                        </div>
                    </form>

This is my backend:

const express = require('express');
const path = require('path');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const sanitizer = require('sanitizer');
const rateLimit = require("express-rate-limit");

const app = express();

app.use('/assets', express.static(path.join(__dirname, 'assets'), {
    setHeaders: function (res) {
      res.set('Content-Type', 'text/css');
    }
  }));

app.use('/images', express.static(path.join(__dirname, 'images'), {
    setHeaders: function (res, path) {
      if (path.endsWith('.jpg')) {
        res.set('Content-Type', 'image/jpeg');
      } else if (path.endsWith('.png')) {
        res.set('Content-Type', 'image/png');
      }
    }
  }));

app.use('/assets/css/images', express.static(path.join(__dirname, 'assets/css/images')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// create a rate limiter middleware
const submissionLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: "Too many submissions from this IP, please try again later"
});
// apply the rate limiter middleware to the / endpoint
app.use('/', submissionLimiter);

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.post('/', (req, res) => {
  const name = sanitizer.sanitize(req.body.name);
  const email = sanitizer.sanitize(req.body.email);
  const type = sanitizer.sanitize(req.body.type) || 'No especifica';
  const make = sanitizer.sanitize(req.body.make) || 'No especifica';
  const model = sanitizer.sanitize(req.body.model) || 'No especifica';
  const year = sanitizer.sanitize(req.body.year) || 'No especifica';
  const message = sanitizer.sanitize(req.body.message);

  const transporter = nodemailer.createTransport({
    host: 'hydra.vivawebhost.com',
    port: 995,
    auth: {
      user: 'info@example.com',
      pass: 'examplepass'
    }
  });

  const mailOptions = {
    from: 'example@gmail.com',
    to: 'info@example.com',
    subject: 'Nueva Consulta',
    text: `Recibiste una nueva consulta. Nombre: ${name}. Email: ${email}. Tipo: ${type}. Marca: ${make}. Modelo: ${model}. Año: ${year}. Mensaje: ${message}.`
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log(error);
      res.status(500).json({ status: 'error', message: 'Error al enviar el correo' });
    } else {
      console.log('Email sent: ' + info.response);
      res.status(200).json({ status: 'success', message: 'Consulta enviada con éxito' });
    }
  });
});
const port = process.env.PORT || 3000;
console.log(`Server running on port ${port}`); // Add this line
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

and this is my JavaScript:

/* Prueba fetch form */

const form = document.querySelector('#form');
const spinner = document.querySelector('#spinner');
const formMessage = document.querySelector('#form-message');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  spinner.style.display = 'block';
  formMessage.style.display = 'none';
  const formData = new FormData(form);
  fetch('/', {
    method: 'POST',
    body: formData
  })
    .then(response => response.json())
    .then(data => {
      spinner.style.display = 'none';
      formMessage.style.display = 'block';
      formMessage.textContent = data.message;
      form.reset();
    })
    .catch(error => {
      spinner.style.display = 'none';
      formMessage.style.display = 'block';
      formMessage.textContent = 'Error al enviar el formulario.';
    });
});

Thank you for your help.

Best regards.

Node.js version

Not applicable.

Example code

Node.js v18.14.0

Operating system

The server is on linux.

Scope

Issue with Form Submission

Module and version

express

preveen-stack commented 1 year ago

express folks can probably provide better insight. Can you please file an issue in https://github.com/expressjs/express/issues