简体   繁体   English

如何使用expressjs,reactjs持久化数据?

[英]How to persist data using expressjs, reactjs?

I have created a simple chat app. 我创建了一个简单的聊天应用程序。 I want to persist data so whenever I refresh it should show the previous chat also. 我想保留数据,因此每当刷新时,它也应该显示上一个聊天记录。 Currently, I am using socket.io, reactjs and nodejs/express. 目前,我正在使用socket.io,reactjs和nodejs / express。 When I refresh the page all chats are gone why so? 当我刷新页面时,所有聊天都消失了,为什么呢? I think my backend is not working in below code. 我认为我的后端无法在下面的代码中工作。 Currently, only client side is working and not backend why so? 当前,只有客户端在工作,而后端没有,为什么呢? What is wrong in server.js? server.js有什么问题?

Code: 码:

server.js: server.js:

const express = require('express');
const socket = require('socket.io');

const app = express();

server = app.listen(5000, function(){
  console.log('server is running on port 5000')
});

io = socket(server);

io.on('connection', (socket) => {
  console.log(socket.id);

  socket.on('SEND_MESSAGE', function(data){
      io.emit('RECEIVE_MESSAGE', data);
  })

});

chat.js: chat.js:

import React, { Component } from 'react'
import './chat.css'
import Icon, {
    Ionicons,
} from 'react-web-vector-icons'
import io from "socket.io-client";

export default class Chat extends Component {

    constructor(props){
        super(props);

        this.state = {
            message: '',
            messages: []
        };

        this.socket = io('localhost:5000');

        this.socket.on('RECEIVE_MESSAGE', function(data){
            addMessage(data);
        });

        const addMessage = data => {
            console.log(data);
            this.setState({messages: [...this.state.messages, data]});
            console.log(this.state.messages);
        };

        this.sendMessage = ev => {
            ev.preventDefault();
            this.socket.emit('SEND_MESSAGE', {
                message: this.state.message
            })
            this.setState({message: ''});
        }

    }

    render() {
        return (
        <div>
                <div id="status"></div>
                <div id="chat">
                    <div className="card">
                        <div id="messages" className="card-block">
                            {this.state.messages.map(message => {
                                    return (
                                        <div className="msgCard">{message.message}</div>
                                    )
                            })}
                        </div>
                    </div>
                    <div className="row">
                        <div className="column">
                            <input id="inputmsg" type="text" placeholder="Enter Message...."
                            value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
                        </div>
                        <div className="column2">
                            <button id="send" className="button" onClick={this.sendMessage}>Send</button>
                        </div>
                    </div>
                </div>
        </div>
        )
    }
}

Note: backend is working on port 5000 and client on 3000 using concurrently. 注意:后端正在同时使用端口5000和客户端3000。 When I go to port 5000 I am getting error 404 why so? 当我进入端口5000时出现错误404,为什么会这样?

Screenshot: 截图:

在此处输入图片说明

Chat app: 聊天应用:

在此处输入图片说明

Your server code not storing chat data anywhere in any db. 您的服务器代码未在任何数据库的任何位置存储聊天数据。 its now act like middleware receiving the message and sending message to client. 现在,它就像中间件一样接收消息并将消息发送到客户端。

you are listening port 5000 but your not handling any incoming requests so its throwing error. 您正在侦听端口5000,但未处理任何传入请求,因此抛出了错误。

You have to save somewhere you data. 您必须将数据保存在某处。 Yes it is possible without a database. 是的,没有数据库也是可能的。 Here I have implemented it using LocalStorage which resides in the browser. 在这里,我使用浏览器中的LocalStorage实现了它。

this.state = {
        // Get previously saved messages.
        message: '',
        messages: JSON.parse(LocalStorage.getItem('messages')) || [],
    };


const addMessage = data => {
        console.log(data);
        this.setState({messages: [...this.state.messages, data]});
        console.log(this.state.messages);
        // Saving to HTML5 LocalStorage
        LocalStorage.setItem('messages' , JSON.stringify(this.state.messages);
    };

I hope it helps. 希望对您有所帮助。 Leave a comment if u face any issue. 如果您遇到任何问题,请发表评论。

To answer your second question first: 首先要回答第二个问题:

Note: backend is working on port 5000 and client on 3000 using concurrently. 注意:后端正在同时使用端口5000和客户端3000。 When I go to port 5000 I am getting error 404 why so ? 当我进入端口5000时出现错误404,为什么会这样?

Your node/express/socket-io backend is running on port 5000. Your dev-server for your react application (which serves HTML/JS/CSS files) is running on port 3000 (I'm assuming). 您的node / express / socket-io后端在端口5000上运行。您的react应用程序(提供HTML / JS / CSS文件)的开发服务器在端口3000(我假设)上运行。 Trying to connect to your node/express/socket-io backend with your browser (which tries to fetch files via HTTP protocol) results in a 404. 尝试使用浏览器连接到您的node / express / socket-io后端(试图通过HTTP协议获取文件)会导致404。

To persist older messages, as others have said, you need to use a db. 如其他人所述,要保留较旧的消息,您需要使用数据库。 either localStorage , which stores the data to PC, server side, you could use in memory storage (just push old message in an array, and replay when user connect), or actual db like mongo, sql, etc. 或者将数据存储到PC,服务器端的localStorage ,您可以在内存存储中使用(只需push旧消息push送到阵列中,然后在用户连接时重播),或实际的数据库(如mongo,sql等)即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM