Развертывание heroku MERN socket.io и socket.io-client
Я понятия не имею, что происходит в журналах heroku, которые говорят мне, что не могут найти node_modules, которые я удалял и переустанавливал несколько раз, приложение работает нормально, даже когда я переключил его на запуск с сервера localhost:5000, вот журналы heroku :
2022-03-09T20:07:45.422964+00:00 приложение[web.1]: код: 'MODULE_NOT_FOUND',
2022-03-09T20:07:45.422964+00:00 приложение[web.1]: requireStack: [
2022-03-09T20:07:45.422964+00:00 приложение[web.1]: '/app/backside/controllers/messageCtrl.js',
2022-03-09T20:07:45.422965+00:00 приложение[web.1]: '/app/backside/routers/messageRouter.js',
2022-03-09T20:07:45.422965+00:00 приложение[web.1]: '/app/backside/server.js'
2022-03-09T20:07:45.422965+00:00 приложение[веб.1]: ]
2022-03-09T20:07:45.422965+00:00 приложение[веб.1]: }
2022-03-09T20:07:45.541860+00:00 heroku[web.1]: Процесс завершен со статусом 1
2022-03-09T20:07:45.594069+00:00 heroku[web.1]: состояние изменено с запуска на сбой
2022-03-09T20:07:45.996702+00:00 heroku[маршрутизатор]: at=код ошибки=H10 desc="Сбой приложения" метод=GET path="/" host=pegr.herokuapp.com request_id=e1675bba-ffa4-456c-b3b0-53af1cbd59c5 fwd="107.127.21.61" dyno=connect=service=статус=503 байта=протокол=https
Вот мой сервер.js
//req dotenv could be messing up some of the back end while placed in server.js
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const cookieparser = require("cookie-parser");
const authRouter = require('./routers/authRouter')
const multer = require("multer");
const userRouter = require('./routers/userRouter')
const postRouter = require('./routers/postRouter')
const commentRouter = require('./routers/commentRouter');
const notifyRouter = require('./routers/notifyRouter');
const messageRouter = require('./routers/messageRouter');
const socketServer = require("./socketServer");
const path = require("path");
const app = express();
app.use(express.json()); // for body parsing..
app.use(cors());
app.use(cookieparser());
//Multer for image uploads
// const storage = multer.diskStorage({
// destination: (req, file, cb) => {
// cb(null, "images");
// },
// filename: (req, file, cb) => {
// cb(null, req.body.name);
// },
// });
// const upload = multer({ storage: storage });
// app.post("/api/upload", upload.single("file"), (req, res) => {
// try {
// return res.status(200).json("File uploded successfully");
// } catch (error) {
// console.error(error);
// }
// });
//routes
const http = require('http').createServer(app)
const io = require('socket.io')(http)
app.use('/api',authRouter)
app.use('/api',userRouter)
app.use('/api',postRouter)
app.use('/api',commentRouter)
app.use('/api',notifyRouter)
app.use('/api',messageRouter)
// -------DEPLOYMENT-------
__dirname = path.resolve();
if(process.env.NODE_ENV === "production"){
app.use(express.static(path.join(__dirname, "/frontside/build")));
app.get('*',(req,res)=>{
res.sendFile(path.resolve(__dirname, "frontside","build","index.html"));
})
}else{
app.get("/", (req,res)=>{
res.send("API is Running Successfully");
});
}
// -------DEPLOYMENT-------
const port = process.env.PORT || 5000;
//changed to from MONGO_URI to URL just to get it to work
const URL = process.env.MONGO_URI;
io.on('connection', socket=>{
socketServer(socket)
})
mongoose.connect(
URL,
{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) throw err;
console.log("db is connected");
}
);
http.listen(port, () => {
console.log(`app is running on ${port}`);
});
вот мой package.json для бэкенда
{
"name": "backside",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "nodemon backside/server.js",
"client": "npm start --prefix frontside",
"dev": "concurrently \"npm start\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix frontside && npm run build --prefix frontside",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"engines": {
"node": "14.18.1"
},
"dependencies": {
"bcrypt": "^5.0.1",
"bcryptjs": "^2.4.3",
"concurrently": "7.0.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.12.12",
"multer": "^1.4.2",
"nodemon": "^2.0.7",
"npm": "^7.20.6",
"path": "^0.12.7",
"socket.io": "^4.1.2",
"uninstall": "^0.0.0"
}
}
Вот мои контроллеры и роутеры, которые якобы пропали.
const conversations = require('../models/conversationModel')
const Messages = require('../models/messageModel')
const messageCtrl = {
createMessage: async(req,res) =>{
try {
const {recipient, text, media} = req.body
if(!recipient || (!text.trim() && media.length === 0 )) return;
const newConversation = await conversations.findOneAndUpdate({
$or:[
{recipients: [req.user._id, recipient]},
{recipients: [recipient, req.user._id]}
]
},{
recipients: [req.user._id, recipient],
text, media
},{
new: true , upsert:true
})
const newMessage = new Messages({
conversation: newConversation._id,
sender:req.user._id,
recipient , text, media
})
await newMessage.save()
res.json({newConversation})
} catch (err) {
return res.status(500).json({msg: err.message})
}
},
getConversations: async(req,res) =>{
try {
const conversation = await conversations.find({
recipients: req.user._id
}).sort('updatedAt').populate('recipients', "avatar fullname username")
res.json({
conversation,
result:conversation.length
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
},
getMessages: async(req,res) =>{
try {
const message = await Messages.find({
$or:[
{
sender:req.user._id, recipient: req.params.id,
},
{
sender: req.params.id, recipient: req.user._id
}
]
}).sort('-createdAt').populate('recipients', "avatar fullname username")
res.json({
message,
result: message.length
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
},
deleteMessages: async(req,res) =>{
try {
await Messages.findOneAndDelete({_id: req.params.id, sender:req.user._id})
res.json({msg:'deleted'})
} catch (err) {
return res.status(500).json({msg: err.message})
}
}
}
module.exports = messageCtrl;
const router = require('express').Router();
const messageCtrl = require('../controllers/messageCtrl')
const auth = require('../middlewares/auth')
router.post('/message', auth, messageCtrl.createMessage)
router.get('/conversations', auth, messageCtrl.getConversations)
router.get('/message/:id', auth, messageCtrl.getMessages)
router.delete('/message/:id', auth, messageCtrl.deleteMessages)
module.exports = router;
мой .gitignore:
.env
/build
/frontside/build
/frontside/node_modules
node_modules/
мой профайл:
web: node backside/server.js