Reputation: 3
I'm now making a code in HTML that saves the value in the database when you type it in input. However, if you enter a value in the input and press the button, the value should be stored in the users table in the user.db file, but it does not work. I made the server Glitch and I saved the HTML file on my computer.
First of all, the code in server.js is this (saved to Glitch and running)
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}`);
});
And client.js and index.html.
client.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>
However, even if you enter a value on the site and press the button, the value is not saved in user.db. I think Glitch and my computer are connected, but I can't save the value. What is the reason?
Value cannot be added to the database.
Upvotes: 0
Views: 30
Reputation: 93
You need to add the "name" attribute to each input field. Without this attribute, the data won't be submitted
Example:
<input id="nickname" name="nickname" placeholder="닉네임">
<input id="password" name="password" placeholder="비밀번호" type="password">
<input id="email" name"email" placeholder="이메일">
Upvotes: 1