Получение ошибки 405 при нажатии кнопки входа в системуHtml

Программисты Html
Ответить
Anonymous
 Получение ошибки 405 при нажатии кнопки входа в систему

Сообщение Anonymous »

Я создаю страницу входа для своего личного проекта Chocolate Shop, но пытаюсь заставить ее работать с Firebase, к которому я ее подключил. Однако я должен получить либо сообщение об ошибке входа в систему, либо сообщение об успешном входе в систему, но продолжает возвращаться как ошибка 405 ERR_HTTP_RESPONSE_CODE_FAILURE 405 (Метод не разрешен).
Я пытался изменить расположение окна в строке 94
window.location.href = 'index.html';

Именно здесь пользователь должен быть перенаправлен на эту страницу после того, как он вошел на эту страницу через файл firebaseAuth.js.
Я предоставил свой код HTML и JS ниже:

HTML-файл (index.html):



Simon's Chocolate Shop










Изображение


Home
Chocolates
Prices
Contact us
About us
Login
Sign Up
[url=javascript:void(0);]☰[/url]


Login


Email:


Password:


Login



© Simon's Chocolate Shop 2022





JS-код (firebaseAuth.js):
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.1 ... ase-app.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/11.1 ... se-auth.js";
import { getFirestore, setDoc, doc } from "https://www.gstatic.com/firebasejs/11.1 ... restore.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/se ... -libraries

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDJ7D03Tdvirt8XE7t244MOV-swdJg7meQ",
authDomain: "simons-chocolate-shop.firebaseapp.com",
projectId: "simons-chocolate-shop",
storageBucket: "simons-chocolate-shop.firebasestorage.app",
messagingSenderId: "481372238801",
appId: "1:481372238801:web:c6700486161321acdfe6f0"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

function showMessage(message, divId) {
var messageDiv = document.getElementById(divId);

messageDiv.style.display = "block";
messageDiv.innerHTML = message;
messageDiv.style.opacity = 1;

setTimeout(function() {
messageDiv.style.opacity = 0;
}, 5000);
}

// Functionality for the sign-up button
const signUp = document.getElementById("submitSignUp");
signUp.addEventListener("click", (event) => {
event.preventDefault();

const email = document.getElementById("registerEmail").value;
const password = document.getElementById("registerPassword").value;
const firstName = document.getElementById("firstName").value;
const lastName = document.getElementById("lastName").value;

const auth = getAuth();
const db = getFirestore();

createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {
const user = userCredential.user;
const userData = {
firstName: firstName,
lastName: lastName,
email: email,
password: password
};

showMessage("Account created successfully", "registerMessage");

const userRef = doc(db, "users", user.uid);

setDoc(userRef, userData).then(() => {
window.location.href = "index.html";
})
.catch((error) => {
console.error("Error writing document: ", error);
});
})
.catch((error) => {
const errorCode = error.code;

if (errorCode === 'auth/email-already-in-use') {
showMessage("Email already in use! Please try another email.", "registerMessage");
}
else {
showMessage(`Error creating account: ${error.message}`, "registerMessage");
}
})
});

// Functionality for the login button
const signIn = document.getElementById('submitSignIn');
signIn.addEventListener('click', (event) => {
event.preventDefault();

const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const auth = getAuth();

signInWithEmailAndPassword(auth, email, password).then((userCredential) => {
showMessage('You have logged in', 'signInMessage');

const user = userCredential.user;

localStorage.setItem('loggedInUserId', user.uid);

window.location.href = 'index.html';
})
.catch((error) => {
const errorCode = error.code;

if (errorCode === 'auth/invalid-credential') {
showMessage("Invalid email or password", "signInMessage");
}
else {
showMessage(`That account doesn't exist`, "signInMessage");
}
})
});

Я также предоставил скриншоты ошибок.
Пользователь нажимает кнопку входа:

Изображение

Возвращается сообщение об ошибке 405:
Изображение

Есть ли у кого-нибудь решение, как это исправить?
Обновление от 01.10.2026: я понял, что мои функции входа и регистрации были объединены в один JS-файл под названием firebaseAuth.js, где это противоречит моим функциям входа в систему поэтому я поместил свою функцию входа в отдельный файл с именем login.js, и кнопка входа работала успешно. :)
Login.js:
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.1 ... ase-app.js";
import { getAuth, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/11.1 ... se-auth.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/se ... -libraries

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDJ7D03Tdvirt8XE7t244MOV-swdJg7meQ",
authDomain: "simons-chocolate-shop.firebaseapp.com",
projectId: "simons-chocolate-shop",
storageBucket: "simons-chocolate-shop.firebasestorage.app",
messagingSenderId: "481372238801",
appId: "1:481372238801:web:c6700486161321acdfe6f0"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

function showMessage(message, divId) {
var messageDiv = document.getElementById(divId);

messageDiv.style.display = "block";
messageDiv.innerHTML = message;
messageDiv.style.opacity = 1;

setTimeout(function() {
messageDiv.style.opacity = 0;
}, 5000);
}

// Functionality for the login button
const signIn = document.getElementById('submitSignIn');
signIn.addEventListener('click', (event) => {
event.preventDefault();

const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
const auth = getAuth();

signInWithEmailAndPassword(auth, email, password).then((userCredential) => {
showMessage('You have logged in', 'signInMessage');

const user = userCredential.user;

localStorage.setItem('loggedInUserId', user.uid);

window.location.href = 'about.html';
})
.catch((error) => {
const errorCode = error.code;

if (errorCode === 'auth/invalid-credential') {
showMessage("Invalid email or password", "signInMessage");
}
else {
showMessage(`That account doesn't exist`, "signInMessage");
}
})
});

signUp.js:
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.1 ... ase-app.js";
import { getAuth, createUserWithEmailAndPassword} from "https://www.gstatic.com/firebasejs/11.1 ... se-auth.js";
import { getFirestore, setDoc, doc } from "https://www.gstatic.com/firebasejs/11.1 ... restore.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/se ... -libraries

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDJ7D03Tdvirt8XE7t244MOV-swdJg7meQ",
authDomain: "simons-chocolate-shop.firebaseapp.com",
projectId: "simons-chocolate-shop",
storageBucket: "simons-chocolate-shop.firebasestorage.app",
messagingSenderId: "481372238801",
appId: "1:481372238801:web:c6700486161321acdfe6f0"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

function showMessage(message, divId) {
var messageDiv = document.getElementById(divId);

messageDiv.style.display = "block";
messageDiv.innerHTML = message;
messageDiv.style.opacity = 1;

setTimeout(function() {
messageDiv.style.opacity = 0;
}, 5000);
}

// Functionality for the sign-up button
const signUp = document.getElementById("submitSignUp");
signUp.addEventListener("click", (event) => {
event.preventDefault();

const email = document.getElementById("registerEmail").value;
const password = document.getElementById("registerPassword").value;
const firstName = document.getElementById("firstName").value;
const lastName = document.getElementById("lastName").value;

const auth = getAuth();
const db = getFirestore();

createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {
const user = userCredential.user;
const userData = {
firstName: firstName,
lastName: lastName,
email: email,
password: password
};

showMessage("Account created successfully", "registerMessage");

const userRef = doc(db, "users", user.uid);

setDoc(userRef, userData).then(() => {
window.location.href = "index.html";
})
.catch((error) => {
console.error("Error writing document: ", error);
});
})
.catch((error) => {
const errorCode = error.code;

if (errorCode === 'auth/email-already-in-use') {
showMessage("Email already in use! Please try another email.", "registerMessage");
}
else {
showMessage(`Error creating account: ${error.message}`, "registerMessage");
}
})
});


Подробнее здесь: https://stackoverflow.com/questions/798 ... is-clicked
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»