POST 405 Method Not Allowed Fetch

370 views Asked by At

I am trying to do a registration form using HTML, JS, NodeJS and SQLite. However, I am using a fetch function to try and post the inputted information into the database, but I keep on getting POST http://127.0.0.1:5500/register 405 (Method Not Allowed). Also, I am getting another error Error: SyntaxError: Unexpected end of JSON input on line 69 (commented on JS code) for some reason as well.

I am attaching my codes below.

JS:

document.addEventListener('DOMContentLoaded', function() {
    const firstNameInput = document.getElementById('firstName');
    const surnameInput = document.getElementById('surname');
    const emailInput = document.getElementById('signUpEmailAddress');
    const passwordInput = document.getElementById('signUpPassword');
    const submitButton = document.getElementById('submitButton');
    const togglePasswordIcon = document.getElementById('togglePassword');
  
    // Function to check if all fields are filled and enable/disable the submit button
    function checkFormValidity() {
        const isValid = firstNameInput.value.trim() !== '' &&
                        surnameInput.value.trim() !== '' &&
                        emailInput.value.trim() !== '' &&
                        passwordInput.value.trim() !== '';
        submitButton.disabled = !isValid;
    }
  
    // Function to handle password visibility toggle
    function togglePasswordVisibility() {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        togglePasswordIcon.classList.toggle('fa-eye-slash');
    }
  
    // Event listeners for input fields
    firstNameInput.addEventListener('input', checkFormValidity);
    surnameInput.addEventListener('input', checkFormValidity);
    emailInput.addEventListener('input', checkFormValidity);
    passwordInput.addEventListener('input', checkFormValidity);
  
    // Event listener for password visibility toggle
    togglePasswordIcon.addEventListener('click', togglePasswordVisibility);
  
    // Function to handle form submission
    function signUpUser(event) {
        event.preventDefault();

        // Get form data
        const firstName = firstNameInput.value.trim();
        const surname = surnameInput.value.trim();
        const email = emailInput.value.trim();
        const password = passwordInput.value.trim();

         // Perform form submission logic here
        // You can send the data to the server using fetch API
        fetch("/register", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                firstName: firstName,
                surname: surname,
                email: email,
                password: password
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log(data);
                console.log('User signed up successfully!');
                // Redirect to a new page or show a success message
            } else {
                console.error('User registration failed.');
                // Handle registration failure, show error message, etc.
            }
        })
        .catch(error => console.error("Error:", error)); //Line 69
        
        // Perform form submission logic here
        // console.log('User signed up!');
        // Redirect to a new page or show a success message
    }
  
    // Event listener for form submission
    document.getElementById('signUpForm').addEventListener('submit', signUpUser);
});

Server.js:

const express = require("express");
const bodyParser = require("body-parser");
const sqlite3 = require("sqlite3").verbose();

const app = express();
const port = 5500;

app.use(bodyParser.json());

// SQLite database setup
const db = new sqlite3.Database("users.db", err => {
    if (err) {
        console.error("Error opening database:", err.message);
    } else {
        console.log("Connected to the database.");
        db.run(`
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                firstName TEXT,
                surname TEXT,
                email TEXT,
                password TEXT
            )
        `);
    }
});

// Handle registration POST request
app.post("/register", (req, res) => {
    const { firstName, surname, email, password } = req.body;

    // Insert user data into the database
    const stmt = db.prepare("INSERT INTO users (firstName, surname, email, password) VALUES (?, ?, ?, ?)");
    stmt.run(firstName, surname, email, password, err => {
        if (err) {
            console.error("Error inserting data:", err.message);
            res.json({ success: false });
        } else {
            console.log("User registered successfully.");
            res.json({ success: true });
        }
        stmt.finalize();
    });
});

// Start the server
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

If anyone is able to help me with this would be greatly appreciated.

Many thanks.

1

There are 1 answers

2
passingthru On

I’ll start with the easiest problem…

Error: SyntaxError: Unexpected end of JSON input on line 69

NB: An empty json file still needs the square brackets “[]” to indicate a state of “empty json data”.

For the other problem…

POST http://127.0.0.1:5500/register 405 (Method Not Allowed)

fetch("/register", {
            method: "POST",

It looks like a URL issue so test with a canonical link like this…

fetch("https://example.com/register", {
            method: "POST",