前提
nodeでホームページを作ろうと頑張っています。htmlで特定のボタンをクリックしたらどのボタンが押されたかを識別し、nodeでデータベース操作をし、出力したいと思っています。
実現したいこと
押されたボタンの通りnodeでデータベース操作をし、その値を返す
発生している問題・エラーメッセージ
ボタンの実装はできたのですが、そのボタンの識別とデーターベース操作ができません。
該当のソースコード
html
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 5 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> 6 <title>sample</title> 7</head> 8<body> 9 <input id="textvalue" type="text"><br> 10 <input id="getbutton" type="submit" value="取得(GET)"> 11<script> 12$(function(){ 13 document.getElementById("getbutton").addEventListener("click", () => { 14 $.ajax({ 15 async: false, 16 url: 'http://localhost:9000', 17 type: 'post', 18 data:{"id": "getbutton"}, 19 dataType: 'json' 20 }).done(function(res){ 21 console.debug(res); 22 }).fail(function(xhr, status, error){ 23 alert(status); 24 }); 25 },'false'); 26}); 27</script> 28</body> 29</html>
js
1//データベース 2const mysql = require('mysql'); 3var express = require('express'); 4var app = express(); 5const connection = mysql.createConnection({ 6 host: 'localhost', 7 user: 'root', 8 password: '', 9 port: 3306, 10 database: 'testdb' 11}); 12 13// 接続 14connection.connect((error) => { 15 if(error){ 16 console.log('error connecting: ' + err.stack); 17 return; 18 } 19 console.log('success'); 20}); 21 22//ajax 23var bodyParser = require('body-parser'); 24 25app.use(bodyParser.urlencoded({extended: false})); 26app.use(bodyParser.json()); 27app.use(function(req, res, next){ 28 res.header("Access-Control-Allow-Origin","*"); 29 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 30 next(); 31}) 32app.post('/',function(req, res){ 33 // var obj = {}; 34 // console.log('body: ' + JSON.stringify(req.body.name)); 35 // var rejson = JSON.stringify(req.body); 36 // res.send(rejson); 37 if(JSON.stringify(req.body.id) == "getbutton"){ 38 //select文 39 app.get('/', function(req, res){ 40 connection.query( 41 "SELECT * FROM t01_users;", 42 (error,results) => { 43 if(error){ 44 console.log('error connecting: ' + error.stack); 45 return; 46 } 47 console.log(results); 48 console.log(results[0].password); 49 } 50 ); 51 res.send(JSON.stringify(results)); 52 }); 53 } 54}); 55// 接続終了 56connection.end(); 57 58app.listen(9000);
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/09/06 12:54