Я пытался реализовать модуль чата в моем приложении. У меня мало опыта работы с полным стеком MERN, и я впервые работаю с socket.io. Но всякий раз, когда я пытаюсь создать чат, он выдает ошибку и не создает чат.
Я пытался найти решение, но не смог найти.
(мне очень жаль, если кода много, я сократил его настолько, насколько это возможно, но я не был уверен, какие части будут иметь отношение к вопросу).
class Chat extends Component {
constructor(props) {
super(props);
this.state = {
modal: false,
chatLists: []
};
//this.socket = io("localhost:8080");
}
componentDidMount() {
// if (this.props.auth.isAuthenticated) {
// this.props.history.push("/dashboard");
// }
axios.get(`/chats/list`).then(res => {
const chatLists = res.data;
this.setState({ chatLists });
});
}
sendChatId(i) {
return <ChatDetail chatId={i} />;
}
render() {
return (
<div className="Chat">
{/* <AppNavbar /> */}
<CreateRoom />
<hr />
<h3>Chat Room List</h3>
<Router>
<ListGroup>
{this.state.chatLists.map(chatList => (
<ListGroupItem tag="a" key={chatList._id}>
<Link to={`/chatDetail`}>
{chatList.roomTitle}
{this.sendChatId(chatList._id)}
</Link>
<Route path={`/chatDetail`} component={ChatDetail} />
</ListGroupItem>
))}
</ListGroup>
</Router>
</div>
);
}
}
Chat.propTypes = {
auth: PropTypes.object.isRequired
//errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
//errors: state.errors
});
export default connect(mapStateToProps)(withRouter(Chat));
У меня есть 3 файла заказа с именами "ChatDetails.js", "ChatList.js" и "CreateRoom.js", для которых idk, если я должен отправить код здесь или нет.
Это модель
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Chat Schema
const ChatSchema = new Schema({
roomTitle: {
type: String,
required: true
},
createdBy: {
type: String,
required: true
}
});
module.exports = Chat = mongoose.model("Chat", ChatSchema);
//const Chat = module.exports = mongoose.model('Chat', ChatSchema);
module.exports.addChatRoom = function(newChat, callback) {
newChat.save(callback);
};
Модель для подробностей чата
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//const config = require('../config/database');
// Chat Detail Schema
const ChatDetailSchema = new Schema({
chatMsg: {
type: String,
required: true
},
msgBy: {
type: String,
required: true
},
chatId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Chat",
required: true
}
});
module.exports = ChatDetail = mongoose.model("ChatDetail", ChatDetailSchema);
//const ChatDetail = module.exports = mongoose.model('ChatDetail', ChatDetailSchema);
module.exports.addChatMsg = function(newMsg, callback) {
newMsg.save(callback);
};
И чат-маршруты
const express = require("express");
const router = express.Router();
//const config = require('../../config/database');
const Chat = require("../../models/Chat");
const ChatDetail = require("../../models/ChatDetail");
const http = require("http").Server(express);
const io = require("socket.io")(http);
//const express = require("express");
//const router = express.Router();
const mongoose = require("mongoose");
const passport = require("passport");
// Post model
//const Post = require("../../models/Post");
// Profile model
//const Profile = require("../../models/Profile");
// get list of all chat room list
/**
* @route GET api/chats/list
* @desc Get all chatrooms list
*/
router.get("/list", (req, res, next) => {
Chat.find()
.sort({ date: -1 })
.then(chats => res.json(chats));
});
/**
* @route POST api/chats/create
* @desc Create a new chat room
* @param {String} roomTitle
* @param {String} createdBy
*/
router.post("/create", (req, res) => {
let newChat = new Chat({
roomTitle: req.body.roomTitle,
createdBy: req.body.createdBy
});
Chat.addChatRoom(newChat, (err, chat) => {
if (err) {
res.json({
success: false,
msg: "Can not create Chat room"
});
} else {
res.json({
success: true,
msg: "Successfully created a chat room"
});
}
});
});
/**
* @route GET api/chats/detail/:id
* @desc Get Chat Details
* @param {String} chatId
*/
router.get("/detail/:id", (req, res, next) => {
const chatId = req.params.id;
Chat.findById(chatId)
.then(function(chat) {
if (chat) {
const queryForMsgs = ChatDetail.find();
queryForMsgs.where("chatId", chatId);
queryForMsgs.populate("chatId");
queryForMsgs.exec(function(err, result) {
if (err) {
res.json("No chat msgs here" + err);
} else {
res.json(result);
}
});
}
})
.catch(err => res.status(404).json({ success: false }));
});
/**
* @route POST api/chats/addMsg/:id
* @desc Add new chat msg with chatRoom Id, username, message
* @param {String} chatId
*/
router.post("/addMsg/:id", (req, res, next) => {
const chatId = req.params.id;
let newMsg = new ChatDetail({
chatId: chatId,
chatMsg: req.body.chatMsg,
msgBy: req.body.msgBy
});
ChatDetail.addChatMsg(newMsg, (err, chatMsgs) => {
if (err) {
res.json({
success: false,
msg: "No msg send"
});
} else {
// res.json ({success: true, msg: 'Successfully Send a msg'});
io.on("connection", function(socket) {
console.log("A New msg send....");
socket.on("getMsgBy", function(data) {
console.log(data);
socket.emit("msgData", { msgBy: data });
});
socket.on("msgToAll", function(data) {
//Send message to everyone
io.sockets.emit("newmsg", data);
});
});
}
});
});
/**
* Delete chat msg from chat detail
* @route DELETE api/chats/delete/:id
* @desc Delete A chat message
* @param {String} chatMsgId
* @return {Boolean}
*/
router.delete("/delete/:id", (req, res) => {
const chatMsgId = req.params.id;
ChatDetail.findById(chatMsgId)
.then(chat => chat.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
/**
* @route POST api/chats/update/:id
* @desc Update chat Messages
* @param {String} chatMsgId
*/
router.post("update/:id", (req, res) => {
const chatMsgId = req.params.id;
ChatDetail.findById(chatMsgId).exec(function(err, result) {
result.set({
chatMsg: req.body.chatMsg,
msgBy: req.body.msgBy
});
result.save(function(err, newResult) {
if (err) {
console.log(err);
} else {
io.on("connection", function(socket) {
console.log("Msg updates....");
socket.on("getMsgBy", function(data) {
console.log(data);
socket.emit("msgData", { msgBy: data });
});
socket.on("msgToAll", function(data) {
//Send message to everyone
io.sockets.emit("newmsg", data);
});
});
}
});
});
});
// test routes
router.get("/test", (req, res, next) => {
res.send("This route works fine");
});
module.exports = router;
И в точке входа приложения, server.js
// Initialize socket.io
const http = require("http").Server(app);
const io = require("socket.io")(http);
// Use Routes
app.use("/api/users", users);
app.use("/api/chats", chats);
app.use("/api/profile", profile);
app.use("/api/posts", posts);
//Whenever someone connects this gets executed
io.on("connection", function(socket) {
console.log("A user connected..........");
//Whenever someone disconnects this piece of code executed
socket.on("disconnect", function() {
console.log("A user disconnected........");
});
});
userChat = [];
io.on("connection", function(socket) {
console.log("A user connected");
socket.on("setMsgBy", function(data) {
console.log(data);
// check this msgBy in chatroom of database
userChat.push(data);
socket.emit("userSet", { msgBy: data });
});
socket.on("msg", function(data) {
//Send message to everyone
io.sockets.emit("newmsg", data);
});
});
Я ожидаю, что пользователь введет имя чата и его имя, чтобы войти в интерфейс.