質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Express

ExpressはNode.jsのWebアプリケーションフレームワークです。 マルチページを構築するための機能セットおよびハイブリッドのWebアプリケーションを提供します。

Q&A

解決済

1回答

514閲覧

Node.js + Expressで構築したサイトがページバックすると、想定動作しなくなる

nsya18kmsk93

総合スコア1

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Express

ExpressはNode.jsのWebアプリケーションフレームワークです。 マルチページを構築するための機能セットおよびハイブリッドのWebアプリケーションを提供します。

0グッド

0クリップ

投稿2023/01/20 05:17

編集2023/01/20 06:25

もしかしたら、凄い初心者な事を聞いているかもしれません、ご了承ください。。。

前提

Node.js + ExpressでサイボウズkintoneのURLを渡して
kintoneに記載されたパラメーターと現在MySQL内に保存しているデータを
突合するページを作ろうとしています。

現在突合自体は出来ていますが、突合結果を表示したページ(result2)から
「back」でURLを入力するトップページに戻った際
次のURLを入力しても動作しない、という現象が発生しています。

検索1度目。481のレコードを確認する。
イメージ説明

結果1度目。無事検索出来て、突合結果も見れる。ここでBackすると・・・
イメージ説明

検索2度目。今度は468のレコードを確認しようとするが
ページ読み込みでクルクルしたまま進まなくなる。
イメージ説明

尚、Node.jsのサービスをリロードすればまた検索出来ます。
また、468のレコードも存在しています。
(2度目で無ければ普通に突合出来ます。)

実現したいこと

「Back」したあとも1度目と同じように動作して欲しいです。

発生している問題・エラーメッセージ

特にエラーメッセージ等は出力されませんが、1度目に検索した際に代入される変数が
2度目には代入されていないことを確認しています。

console.log(obj_no) ← kintoneに登録されている番号 console.log(obj_name) ← kintoneに登録されている名前 console.log(db_name) ← MySQLに登録されている名前

1度目の検索の際のconsole.logの結果

0562 ■■■■クリニック ■■■■クリニック

2度目の検索の際はconsole.logに何も出力されません。

該当のソースコード

メインとなるtest2.jsです。(段組み汚くてすみません・・・)

Node.js

1// App Definition 2const express = require('express'); 3const http = require('http'); 4const fs = require('fs'); 5const ejs = require('ejs'); 6const url = require('url'); 7const favicon = require('serve-favicon'); 8const path = require('path'); 9const bodyParser = require('body-parser'); 10const document = require('document'); 11const mysql = require('mysql'); 12const { exec } = require('child_process') 13const { KintoneRestAPIClient } = require('@kintone/rest-api-client'); 14 15const app = express(); 16app.use(express.static(path.join(__dirname, 'public'))); 17app.use(bodyParser.urlencoded({ 18 extended: true 19})); 20 21// Engine Definition 22app.engine('ejs',ejs.renderFile); 23 24// Database Login 25const con = mysql.createConnection({ 26 host: 'localhost', 27 database: 'DB', 28 user: 'root', 29 password: 'password1' 30}); 31 32// API Login 33const client = new KintoneRestAPIClient({ 34 baseUrl: 'https://xxxxxxxx.s.cybozu.com', 35 auth: { 36 username: 'user', 37 password: 'password2' 38 }, 39 clientCertAuth: { 40 pfxFilePath: './file.pkcs12.pfx', 41 password: 'password3' 42 } 43}); 44 45// Test Form Top Page Definition 46app.get("/", function(req, res){ 47 res.render('test2.ejs', 48 { 49 "title":"test用フォーム", 50 "message":"testフォーム" 51 } 52 ); 53}); 54 55let kintone_id; 56 57let kin_id = ""; 58let APP_ID = ""; 59let RECORD_ID = ""; 60let param_setup = ""; 61 62let obj = ""; 63let obj_bikou = ""; 64 65let com_url = ""; 66 67let kin_id2 = ""; 68let APP_ID2 = ""; 69let RECORD_ID2 = ""; 70let param = ""; 71 72let obj2 = ""; 73let obj_no = ""; 74let obj_name = ""; 75 76let com_no = ""; 77let com_name = ""; 78 79let sql_current = ""; 80 81let db_no = ""; 82let db_name = ""; 83 84let judge_no = ""; 85let judge_name = ""; 86 87// Result Page Definition 88app.post("/result2", function(req, res){ 89 const command = "echo \"" + req.body.url + "\" | awk -F'[=&]' '{ print $2 }'" 90 exec(command, function(err, results) { 91 if (err) { 92 console.log("There is no such Kintone's page!!") 93 return 94 } else { 95 kintone_id = results.replace(/\r?\n/g,""); 96 kin_id = Number(kintone_id); 97 APP_ID = 90; 98 RECORD_ID = kin_id; 99 param_setup = { 100 "app": APP_ID, 101 "id": RECORD_ID 102 }; 103 client.record.getRecord(param_setup).then((resp) => { 104 obj = JSON.parse(JSON.stringify(resp.record)); 105 obj_bikou = obj.文字列__複数行__12.value 106 107 com_url = "echo \"" + obj_bikou + "\" | sed -e 's/\\\\n/\\n/g' | grep -B1 \"SSH\" | awk -F'=' '{ print $2 }' | sed -e 's/^\\s//g' -e 's/\\s$//g' | tr -d '\\n'" 108 109 exec(com_url, function(err, res_url) { if (err) { console.log("There is no such Kintone's page!!"); return } else { 110 kintone_id2 = res_url.replace(/\r?\n/g,""); 111 kin_id2 = Number(kintone_id2); 112 APP_ID2 = 68; 113 RECORD_ID2 = kin_id2; 114 param = { 115 "app": APP_ID2, 116 "id": RECORD_ID2 117 }; 118 client.record.getRecord(param).then((resp2) => { 119 obj2 = JSON.parse(JSON.stringify(resp2.record)); 120 obj_no = obj2.id.value 121 obj_name = obj2.name.value 122 123 com_no = "echo \"" + obj_no + "\" | sed -e 's/^\\s//g' -e 's/\\s$//g' | tr -d '\\n'" 124 com_name = "echo \"" + obj2.name.value + "\" | sed -e 's/^\\s//g' -e 's/\\s$//g' | tr -d '\\n'" 125 126 exec(com_no, function(err, res_no) { if (err) { console.log(err.stack); } else { 127 exec(com_name, function(err, res_name) { if (err) { console.log(err.stack); } else { 128 con.connect(function(err) { 129 if (err) { 130 } else { 131 sql_current = "SELECT * FROM facility WHERE no = \'" + res_no + "\';" 132 133 con.query(sql_current, function (err, results) { if (err) { console.log(err.stack); } else { 134 if (results.length == 0) { 135 db_no = "no DB entry" 136 db_name = "no DB entry" 137 138 judge_no = "<span style=\"font-weight: bold; color: MidnightBlue;\">無</span>" 139 judge_name = "<span style=\"font-weight: bold; color: MidnightBlue;\">無</span>" 140 141 console.log(obj_no) 142 console.log(obj_name) 143 144 console.log(db_no) 145 console.log(db_name) 146 147 res.render('result3.ejs', 148 { 149 "title" : "確認画面", 150 "no" : res_no, 151 "name" : res_name, 152 153 "r_no" : db_no, 154 "r_name" : db_name, 155 156 "j_no" : judge_no, 157 "j_name" : judge_name, 158 } 159 ); 160 } else { 161 db_no = "&nbsp;番号で検索している為<br>必ず一致する&nbsp;" 162 db_name = results[0].name 163 164 var judge_no = "&nbsp;---&nbsp;" 165 if (res_name == db_name) { var judge_name = "同" } else { var judge_name = "<span style=\"font-weight: bold; color: red;\">違</span>" } 166 167 res.render('result3.ejs', 168 { 169 "title" : "確認画面", 170 "no" : res_no, 171 "name" : res_name, 172 173 "r_no" : db_no, 174 "r_name" : db_name, 175 176 "j_no" : judge_no, 177 "j_name" : judge_name, 178 } 179 ); 180 181 console.log(obj_no) 182 console.log(obj_name) 183 184 console.log(db_no) 185 console.log(db_name) 186 187 } 188 }}); 189 }; 190 }); 191 }}); 192 }}); 193 }); 194 }}); 195 }).catch((err) => { 196 console.log("Display err"); 197 console.log("----------------------------------------------------------"); 198 console.log(err); 199 console.log("----------------------------------------------------------"); 200 }); 201 }; 202 }); 203}); 204 205const server = app.listen(1234, function(){ 206 console.log('Server is running!'); 207});

Topページのviews/test2.ejsです。

<!DOCTYPE html> <html lang="ja"> <head> <title><%= title %></title> <link rel="stylesheet" href="/css/page.css"> <link rel="stylesheet" href="/css/input.css"> </head> <body class="wrapper"> <h1 align="center"><%= message %>用マニュアル作成ツール</h1> <form action="/result2" method="post"> <table align="center"> <tr> <th>Heading</th> <td>Value</td> </tr> <tr> <th>URL</th> <td><input type="text" name="url" value=""></td> </tr> </table> <br> <div align="center"> <input type="submit" class="button" value="確認"> </div> </form> </body> </html>

試したこと

引数の代入の問題かな?と思い
constで直代入していた変数を一旦外出しで
letで定義 + 初期化してみましたが、ダメでした。

補足情報(FW/ツールのバージョンなど)

cat /etc/redhat-release

CentOS Linux release 8.3.2011

node -v

v10.24.0

mysql --version

mysql Ver 8.0.26 for Linux on x86_64 (Source distribution)

npm info express version

4.18.2

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

nsya18kmsk93

2023/01/20 05:18

文字数制限かかったので。 突合画面のviews/result3.ejsです。 ``` <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title><%= title %></title> <link rel="stylesheet" href="/css/page.css"> <link rel="stylesheet" href="/css/input.css"> <style> p { font-family : 'Noto Sans JP', sans-serif; text-indent : 1em; width : 100%; margin-left : 0%; margin-right : 0%; } table{ width : 100%; } table th{ font-size : 50%; width : 25%; background : #52C2D0; padding-left : 1em; } table th:after{ border-left : 10px solid #52C2D0; } table td{ font-size : 90%; width : 45%; padding : 10px 20px; } </style> </head> <body class="wrapper"> <h1>確認画面</h1> <p>登録内容の確認です。問題なければ「Go!!!」をクリックして下さい。</p> <table align="center"> <tr> <th>Heading</th> <td>Value</td> <td>Current Record</td> <td>Judge</td> </tr> <tr> <th>番号</th> <td><%= no %></td> <td><%- r_no %></td> <td><%- j_no %></td> </tr> <tr> <th>名前</th> <td><%= name %></td> <td><%= r_name %></td> <td><%- j_name %></td> </tr> </table> <br> <div align="center"> <button type="button" class="button" onclick="history.back()">Back</button> <button type="button" class="button" onclick="location.href='http://172.31.9.150:1234/check/'">Go!!!</button> </div> </form> </body> </hmtl> ```
guest

回答1

0

自己解決

結論から言うと、DBへの再接続が出来なかったことが原因でした。
javascriptのMySQLの仕様上、再接続は出来ないそう・・・。

「Re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.」
出典元:https://github.com/mysqljs/mysql/blob/master/Readme.md#server-disconnects

なので、con.connectしないで、いきなりcon.queryを投げてやるとうまくいきました。
こうすると、セッション単位で接続が終了する為、接続も再接続も無い為、問題なく処理されるようです。

これを

con.connect(function(err) { if (err) { } else { sql_current = "SELECT * FROM facility WHERE no = \'" + res_no + "\';" con.query(sql_current, function (err, results) { if (err) { console.log(err.stack); } else { if (results.length == 0) { . . . } }}); }; });

こうしました。

sql_current = "SELECT * FROM hotel WHERE hotel_no = \'" + res_hotelno + "\';" con.query(sql_current, function (err, results) { if (err) { console.log(err.stack); } else { if (results.length == 0) { . . . } }});

本当はコネクションプールの実装を検討すべきなのでしょうが、とりあえず、今回はこれでOKとします。。。

投稿2023/01/24 03:58

nsya18kmsk93

総合スコア1

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問