该值未存储在数据库中

问题描述 投票:0回答:1

我现在正在 HTML 中编写代码,当您在输入中键入值时,该代码会将值保存在数据库中。 但是,如果您在输入中输入一个值并按下按钮,该值应该存储在 user.db 文件的 users 表中,但它不起作用。 我制作了服务器故障并将 HTML 文件保存在我的计算机上。

首先server.js中的代码是这样的(保存到Glitch并运行)

const express = require('express');
const sqlite3 = require('sqlite3').verbose();

const app = express();
const port = process.env.PORT || 3000;

// SQLite 데이터베이스 연결
const db = new sqlite3.Database('user.db');

// POST 요청을 처리하는 미들웨어 설정
app.use(express.json());

// 클라이언트로부터의 POST 요청 처리
app.post('/register', (req, res) => {
    const { nickname, password, email } = req.body;

    // 데이터베이스에 데이터 삽입
    db.run(`INSERT INTO users(username, email, password) VALUES (?, ?, ?)`, [nickname, email, password], function (err) {
        if (err) {
            return console.error('Error inserting data into database:', err.message);
        }
        // 데이터베이스에 성공적으로 삽입된 경우
        console.log(`A row has been inserted with rowid ${this.lastID}`);
        res.json({ message: 'Data inserted successfully' });
    });
});

// 서버 시작
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

还有 client.js 和 index.html。

客户端.js

function sendData() {
    const nickname = document.getElementById('nickname').value;
    const password = document.getElementById('password').value;
    const email = document.getElementById('email').value;

    // 데이터를 객체로 만들어 JSON 형식으로 변환
    const data = {
        nickname: nickname,
        password: password,
        email: email
    };

    // 서버에 POST 요청을 보냄
    fetch('https://carnelian-abalone-periwinkle.glitch.me/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log('Server response:', data);
        // 여기서 필요한 추가 작업을 수행할 수 있습니다.
    })
    .catch(error => {
        console.error('Error sending data to server:', error);
    });
}

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>회원가입</title>
    </head>
    <body>
        <input id="nickname" placeholder="닉네임">
        <input id="password" placeholder="비밀번호" type="password">
        <input id="email" placeholder="이메일">
        <button onclick="sendData()">가입</button>

        <script src="client.js"></script>
    </body>
</html>

但是,即使您在网站上输入一个值并按下按钮,该值也不会保存在 user.db 中。 我认为 Glitch 和我的电脑已连接,但我无法保存该值。 原因是什么?

无法将值添加到数据库。

html database sqlite input glitch.com
1个回答
0
投票

您需要为每个输入字段添加“名称”属性。没有这个属性,数据不会提交

示例:

<input id="nickname" name="nickname" placeholder="닉네임">
<input id="password" name="password" placeholder="비밀번호" type="password">
<input id="email" name"email" placeholder="이메일">
© www.soinside.com 2019 - 2024. All rights reserved.