hi i have node server and i want to pass data with socket io but it not wor this is my code :
const express = require(“express”);
const mongoose = require(“mongoose”);
const socketio = require(“socket.io”);
const http = require(“http”);
const userRoutes = require(“./Routs/UserRouts”);
const newsRoutes = require(“./Routs/NewsRouts”);
const app = express();
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
app.use(express.json());
app.use(“/api/users”, userRoutes);
app.use(“/api/news”, newsRoutes);
io.on(“connection”, (socket) => {
console.log(“a user connected”);
// Emit an event to client to confirm connection
socket.emit(“connected”, { message: “You are connected!” });
// Listen for ‘news added’ event emitted by client
socket.on(“news added”, (data) => {
console.log(data);
// Do something with the new news data, e.g. save to database
// Emit 'news updated' event to all connected clients, including sender
io.emit("news updated", { message: "A new news item has been added!" });
});
// Listen for ‘disconnect’ event emitted by client
socket.on(“disconnect”, () => {
console.log("user disconnected");
});
});
const PORT = process.env.PORT || 5000;
mongoose
.connect(“mongodb://localhost:27017/firstFullstack”)
.then(() => {
console.log("Connected to database");
server.listen(PORT, () =>
console.log(`Server is running on port: ${PORT}`)
);
})
import React, { useState, useEffect } from “react”;
import io from “socket.io-client”;
import {
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
} from “@mui/material”;
const socket = io(“http://localhost:5000/api/news”); // replace with your server URL
function NewsTable() {
const [news, setNews] = useState([]);
useEffect(() => {
socket.on("newsUpdate", (updatedNews) => {
setNews(updatedNews);
});
return () => {
socket.off("newsUpdate");
};
}, []);
return (
<TableContainer component={Paper}>
<Table aria-label='news table'>
<TableHead>
<TableRow>
<TableCell>Title</TableCell>
<TableCell>News</TableCell>
<TableCell>UserName</TableCell>
<TableCell>Resurce</TableCell>
<TableCell>Language</TableCell>
<TableCell>Protection Level</TableCell>
<TableCell>Priority</TableCell>
<TableCell>Media</TableCell>
</TableRow>
</TableHead>
<TableBody>
{news.map((n) => (
<TableRow key={n._id}>
<TableCell>{n.Title}</TableCell>
<TableCell>{n.News}</TableCell>
<TableCell>{n.UserName}</TableCell>
<TableCell>{n.Resurce}</TableCell>
<TableCell>{n.Language}</TableCell>
<TableCell>{n.ProtectionLevel}</TableCell>
<TableCell>{n.priority}</TableCell>
<TableCell>{n.Media}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
export default NewsTable;
const express = require(“express”);
const router = express.Router();
const newsmodel = require(“../models/News.model”);
const { body, validationResult } = require(“express-validator”);
const cors = require(“cors”);
router.use(cors());
// Socket.io integration
const server = require(“http”).createServer();
const io = require(“socket.io”)(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on(“connection”, (socket) => {
console.log(“A client has connected.”);
socket.on(“disconnect”, () => {
console.log("A client has disconnected.");
});
});
// get all news
router.get(“/”, async (req, res) => {
try {
const allnews = await newsmodel.find();
if (!allnews) {
return res.status(404).json({
Date: null,
message: "users not found",
});
}
res.status(200).json({ Date: allnews });
} catch (error) {
res.status(500).json({ Date: null, message: "News not found", error });
}
});
// get one
router.get(“/:id”, async (req, res) => {
try {
const oneuser = await newsmodel.findById(req.params.id);
if (!oneuser) {
return res.status(404).json({
Date: null,
message: "news with id not found",
});
}
res.status(200).json({ data: oneuser });
} catch (error) {
res
.status(500)
.json({ Date: null, message: "technical error", error });
}
});
// insert news post
router.post(“/add”, async (req, res) => {
try {
const addnews = await new newsmodel({
Title: req.body.Title,
News: req.body.News,
UserName: req.body.UserName,
Resurce: req.body.Resurce,
Language: req.body.Language,
ProtectionLevel: req.body.ProtectionLevel,
priority: req.body.priority,
Media: req.body.Media,
});
const newnews = await addnews.save();
io.emit("newsAdded", newnews);
res.json({ data: newnews, message: "news Added successfully" });
} catch (error) {
res
.status(500)
.json({ message: "An error occurred while adding the news user" });
}
});
// delete one
router.delete(“/:id”, async (req, res) => {
try {
const userfordelet = await newsmodel.findByIdAndDelete(req.params.id);
if (!userfordelet) {
return res.status(404).json({ data: null, message: "News not Found" });
}
io.emit("newsDeleted", req.params.id);
res.status(200).json({ data: "News deleted successfully" });
} catch (error) {
res.status(500).json({ data: null, message: "Technical error", error });
}
});
// update news by id
router.put(“/:id”, async (req, res) => {
try {
const updatedNews = await newsmodel.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
}
);
if (!updatedNews) {
return res.status(404).json({ data: null, message: "News not Found" });
}
res.status(200).json({ data: updatedNews, message: "News updated successfully" });
} catch (error) {
res
.status(500)
.json({ data: null, message: "Technical error", error: error });
}
});
module.exports = router;
i want to update data row automatically but data not show from data base