Answer the question
In order to leave comments, you need to log in
How to get data from DB without restarting the server?
In short, I'm creating a simple chat in which:
1) the user enters text, submit.
2) the socket writes to the database what the client entered and returns the same
3) when refreshing the page , the records that were sent earlier should be
written
4) and I have to restart the server (ctrl + c / node app) so that the records appear
Template
<div class="form">
<form action="">
<input class="m" type="text" placeholder="Введите сообщение...">
<button class="send" type="submit">Отправить</button>
</form>
</div>
<div class="sms">
<h3>
<% for (var i = 0; i < smsText.length; i++) { %>
<p><%= smsText[i].text %></p>
<% } %>
</h3>
</div>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
<code lang="javascript">
$(function () {
var socket = io();
$('form').submit((e) => {
e.preventDefault();
socket.emit('chat message', $('.m').val());
$('.m').val('');
return false;
});
socket.on('chat message', function(msg){
$('.sms').append($('<li>').text(msg));
});
});
</code>
</script>
// Chat
var reqDB = 'SELECT * FROM messages';
db.query(reqDB, (err, result) => {
if (err) throw err;
for(let i=0; i < result.length; i++){
result[i].text;
}
// Chat render
app.get('/chat', function (req, res) {
res.render('chat', {
smsText: result
});
});
});
// Socket Connect
io.on('connection', function (socket) {
console.log('Socket Run...')
// Send sms
socket.on('chat message', function(msg, cl){
let sql = `INSERT INTO messages (id, text) VALUES (NULL, '${msg}')`;
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
console.log('SMS send! YES!!!');
})
io.emit('chat message', msg);
});
// Disconnect
socket.on('disconnect', function(){
console.log('Socket STOP!');
});
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question