I can’t transfer the data from the registration form further

  Kiến thức lập trình

I’m using node js and when I want to transfer data from the form, it is not written, a server error pops up. the server is deployed on the azure platform.
Everything seems to be allowed on the platform, but I didn’t find anything on the Internet about it

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>markus</title>
  <link rel="stylesheet" type="text/css" href="/css/style.css">

</head>
<body>
  <div class="img"></div>

  <a href="#" type="button" class="google-login"></a>

  <div class="container">
    <div class="box">
        <h2>Реєстрація</h2>
        <form id="registrationForm" action="/register" method="POST">
            <div>
                <input type="text" name="first_name" required>
                <span>Ім'я</span>
                <i></i>

            </div>
            
            <div>
                <input type="text" name="last_name" required>
                <span>Прізвище</span>
                <i></i>
            </div>

            <div>
                <input type="email" name="email" required>
                <span>Поштова скринька</span>
                <i></i>
            </div>

            <div>
                <input type="password" name="password" required>
                <span>Пароль</span>
                <i></i>
            </div>

            <input type="submit" class="register" value="Надіслати" name="registerButton">
        </form>
    

        <div class="box-form">
            <h2>Увійти</h2>
            <form id="loginForm" action="/login" method="POST">
                <div>
                    <input type="email" name="email" required>
                    <span>Поштова скринька</span>
                    <i></i>
                </div>

                <div>
                    <input type="password" name="password" required>
                    <span>Пароль</span>
                    <i></i>
                </div>

                <input type="submit" value="Надіслати" name="loginButton">

                <a href="№" type="button" class="Face-auntefication"></a>
            </form>
            <div class="close"></div>
        </div>
    </div>
</div>
<script src="/js/form.js"></script>
</body>
</html>


server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const database = require('./DataBase');
const cors = require('cors'); // Додайте цей рядок



const app = express();
app.use(cors({
  origin: 'https://example.com', // Замініть на домен вашого клієнтського додатку
  methods: ['GET', 'POST'], // Дозволені методи (GET, POST)
  allowedHeaders: ['Content-Type'], // Дозволені заголовки
}));


// Parsing POST request data
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


// Serving static files (CSS and JS)
app.use(express.static(path.join(__dirname, ''), {
  setHeaders: (res, path, stat) => {
    if (path.endsWith('.css')) {
      res.setHeader('Content-Type', 'text/css');
    } else if (path.endsWith('.js')) {
      res.setHeader('Content-Type', 'application/javascript');
    }
  },
  fallthrough: false
}));

app.get('/', function(req, res) {
  const op = {
    root: path.join(__dirname, '') 
  };
  const file = "/index.html";
  res.sendFile(file, op, function(err) {
    if (err) {
      res.status(500).send(err);
    }
  });
});

// Route for handling registration request
app.post('/register', async (req, res) => {
  const { first_name, last_name, email, password } = req.body;
  const result = await database.registerUser(first_name, last_name, email, password);
  if (result) {
    res.status(200).send('Користувач зареєстрований успішно');
  } else {
    res.status(500).send('Помилка реєстрації користувача');
  }
});


// Route for handling login request
app.post('/login', async (req, res) => {
  const { email, password } = req.body;
  const user = await database.loginUser(email, password);
  if (user) {
    res.status(200).send('Користувач увійшов в систему успішно');
  } else {
    res.status(401).send('Неправильний email або пароль');
  }
});

// Set the port for the server
const PORT = process.env.PORT || 3000;

// Start the server
app.listen(PORT, () => {
  console.log(`Сервер запущено на порті ${PORT}`);
});


form.js
window.onload = () => {
    const form = document.querySelector(".box-form");

    document.querySelector(".box-form h2").onclick = () =>
        form.classList.add("box-form-open");

    document.querySelector(".close").onclick = () =>
        form.classList.remove("box-form-open");

    const registrationForm = document.getElementById("registrationForm");
    const loginForm = document.getElementById("loginForm");

    registrationForm.addEventListener("submit", function (e) {
        e.preventDefault();
        sendData(this, "/register");
    });

    loginForm.addEventListener("submit", function (e) {
        e.preventDefault();
        sendData(this, "/login");
    });

    function sendData(form, endpoint) {
        const formData = new FormData(form);
        const xhr = new XMLHttpRequest();
        xhr.open("POST", endpoint);
        xhr.setRequestHeader(
            "Content-Type",
            "application/x-www-form-urlencoded"
        );

        xhr.onload = function () {
            if (xhr.status === 200) {
                console.log("Request successful");
                alert(xhr.responseText); // Повідомлення про успішну реєстрацію / вхід в систему
            } else {
                console.error("Request failed");
                console.log(xhr);
                console.log(xhr.responseText);
                console.log(formData);
                alert("Помилка сервера"); // Повідомлення про помилку сервера
            }
        };

        xhr.open("POST", endpoint); // Change the request method to "POST"

        xhr.send(new URLSearchParams(formData).toString());
    }
};


DataBase.js
const sql = require("mssql");
require("dotenv").config();
const fs = require('fs');

// Create a SQL Server connection pool
const config = {
  user: "andryushka",
  password: "gensy[eqkj#2022",
  server: "hitori.database.windows.net",
  database: "mydb",
  options: {
    encrypt: false
  }
};

// Connect to the database and assign the pool
const pool = async () => {
  try {
    const pool = await sql.connect(config);
    console.log('Connected to the database'); // Added: Connection successful message
    return pool;
  } catch (error) {
    console.error('Error connecting to the database:', error);
    throw error;
  }
};

// Register a new user
async function registerUser(first_name, last_name, email, password) {
  try {
    const dbPool = await pool(); // Wait for the pool to be created
    const request = dbPool.request(); // Use the pool object
    request.input("first_name", sql.NVarChar, first_name);
    request.input("last_name", sql.NVarChar, last_name);
    request.input("email", sql.NVarChar, email);
    request.input("password", sql.NVarChar, password);
    const result = await request.query(`
      INSERT INTO [user] (first_name, last_name, email, password)
      VALUES (@first_name, @last_name, @email, @password);
    `);
    console.log('User registered successfully'); // Added: Registration success message
    return result.rowsAffected;
  } catch (error) {
    console.error('Error registering user:', error);
    throw error;
  }
}

// Login user
async function loginUser(email, password) {
  try {
    const dbPool = await pool(); // Wait for the pool to be created
    const request = dbPool.request(); // Use the pool object
    request.input("email", sql.NVarChar, email);
    request.input("password", sql.NVarChar, password);
    const result = await request.query(`
      SELECT * FROM [user] WHERE email = @email AND password = @password;
    `);
    if (result.recordset.length === 0) {
      console.log('User not found or incorrect password'); // Added: Login failure message
      return null;
    }
    const user = result.recordset[0];
    console.log('User logged in successfully'); // Added: Login success message
    return user;
  } catch (error) {
    console.error('Error logging in user:', error);
    throw error;
  }
}

module.exports = {
  registerUser,
  loginUser
};

enter image description here
enter image description here
generates an error that the server does not support the POST method

New contributor

Andrey Kozynyy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT