我正在使用带有Rails的Node.js作为基本聊天应用。现在当我刷新页面时,所有消息都被删除。所以我想使用AJAX将消息存储在rails数据库中。 我怎样才能做到这一点?
nodejs / index.js
console.log("Server is starting...");
const http = require('http');
const hostname = '0.0.0.0';
const port = '8000';
console.log("Creating server...");
const server = http.createServer().listen(port, hostname);
console.log('chat server running on '+ hostname + ':' + port);
let socketList = require('socket.io').listen(server);
socketList.sockets.on('connection', function (socket) {
console.log('connection received');
console.log('socket in node = ', socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
socket.on('join_room', function (data) {
socket.join(data.chatroom);
socketList.in(data.chatroom).emit('user_joined', {
user_email: data.user_email,
chatroom: data.chatroom
});
});
socket.on('send_message', function (data) {
console.log(data.message, data.user_email);
socketList.in(data.chatroom).emit('receive_message', {
message: data.message,
user_email: data.user_email
});
});
});
导轨/ application.js中
window.addEventListener('load', function (ev) {
var user_email = $('#current_user_email').html(); // checking if user login
if(user_email){
var socket = io.connect('http://0.0.0.0:8000');
console.log('socket in rails = ' , socket);
socket.on('connect', function () {
console.log('connection established to node server');
});
socket.emit('join_room',
{
user_email: user_email,
chatroom: 'home'
});
socket.on('user_joined', function (data) {
console.log(data.user_email + ' joined ' + data.chatroom);
});
$('#send-message').click(function () {
let msg = $('#chat-message-input').val();
if(msg !==''){
socket.emit('send_message', {
message: msg,
user_email: user_email,
chatroom: 'home'
});
}
$('#chat-message-input').val('');
});
socket.on('receive_message', function (data) {
console.log(data.user_email, data.message);
let newMessage = $('<li>');
let messageType = 'other-message';
if (data.user_email === user_email){
messageType = 'self-message';
}
newMessage.addClass(messageType);
newMessage.append($('<span>', {
'html': data.message
}));
newMessage.append($('<sub>', {
'html': data.user_email
}));
$('#chat-messages-list').append(newMessage);
});
还有哪些不同的方法可用于在数据库中存储消息? 我们还可以使用Node.js直接存储在Rails数据库中吗?
答案 0 :(得分:1)
不会写代码,但基本上你可以开始:
rails g scaffold Chat name:text chat:text
然后用ajax发布到/chat.json设置数据,如{name:user_name,chat:texxt}
然后你还需要询问来自/chat.json的所有用户聊天 你还需要在索引函数中写入rails
if params[:id]) do
@chat = Chat.find(name:username)
else
@chat = Chat.all
end
然后向用户显示这些消息 但这是让你去的基本概念