我正在尝试使用 HTML、JS、NodeJS 和 SQLite 制作注册表单。但是,我正在使用获取函数尝试将输入的信息发布到数据库中,但我不断收到 POST http://127.0.0.1:5500/register 405(不允许方法)。另外,由于某种原因,我还收到另一个错误 Error: SyntaxError: Unexpected end of JSON input on line 69 (commented on JS code)。
我在下面附上我的代码。
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);
});
服务器.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}`);
});
如果有人能够帮助我,我将不胜感激。
非常感谢。
我将从最简单的问题开始......
错误:语法错误:第 69 行 JSON 输入意外结束
注意:空的 json 文件仍然需要方括号“[]”来表示“空 json 数据”的状态。
对于另一个问题...
POST http://127.0.0.1:5500/register 405(不允许的方法)
fetch("/register", {
method: "POST",
它看起来像一个 URL 问题,所以使用像这样的规范链接进行测试......
fetch("https://example.com/register", {
method: "POST",