ExpressでCRUD
git clone https://github.com/beginnerP765/express_crud.git
git clone https://github.com/beginnerP765/express_crud.git
データベースとテーブルを作成するには、以下のコードを実行するか、app.jsに追加します。
app.jsに追加した場合は、アプリの初回起動時にデータベースとテーブルが作成されます。
const mysql = require('mysql2/promise');
(async () => {
const pool = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
});
find_db = 'SHOW DATABASES LIKE "exapp"';
create_db = 'CREATE DATABASE exapp';
use_table = 'USE exapp';
create_table = 'CREATE TABLE cms (id INT AUTO_INCREMENT, title VARCHAR(255) NOT NULL, content VARCHAR(255) NOT NULL, PRIMARY KEY (id));'
try {
const [results, fields] = await pool.query(find_db);
// データベースがなければデータベースとテーブルを作成
if(!results.length){
await pool.query(create_db);
await pool.query(use_table);
await pool.query(create_table);
}
} catch (err) {
console.log(err);
}
pool.end()
})();
削除ページを経由せずにaタグをクリックしてデータを削除するには、以下のようにします。
// 削除の送信処理を以下のように変更
router.post('/delete/:id', (req, res, next) => {
let id = req.params.id;
(async () => {
try {
const [results, fields] = await pool.query('DELETE FROM cms WHERE id = ?', id);
res.redirect('/cms');
} catch (err) {
console.log(err);
}
})();
});
index.jsを以下のように変更し、delete.ejsのファイルを削除します。
<!-- aタグでsubmitするためのjavascriptを追加 -->
<script>
function sendPost(event) {
event.preventDefault();
if(confirm('削除しますか?')){
let form = document.createElement('form');
form.action = event.target.href;
form.method = 'post';
document.body.appendChild(form);
form.submit();
return true;
}else{
alert('キャンセルされました');
return false;
}
}
</script>
... 中略 ...
<!-- deleteページへのリンクを以下のように変更 -->
<a href="/cms/delete/<%= obj.id %>" onclick="sendPost(event)">delete</a>