Reputation: 1
I am building live chat app, and It is working, and I want to run it on vercel. Everything is working fine on localhost, but it is not working on vercel or netlify.
This is my backend part folder structure.
Like everyone says, I made vercel.json file in root of folder and here it is code.
{
"version": 2,
"builds": [
{
"src": "../backend/server.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/"
}
]
}
While finishing deploying on vercel, I added also env.variables.
But when deploying is finished, I always have this error. https://backend-chat-app-rouge.vercel.app/
I don't have any errors or warnings on Biulding logs on Vercel.
I think problem might be realted to this from vercel.json : "src": "../backend/server.js", because I need to import files like this:
EDIT
server.js file:
const PORT = process.env.PORT || 6001;
const dotenv = require(`dotenv`);
dotenv.config({ path: `./config.env` });
const app = require(`../backend/app`);
const mongoose = require(`mongoose`);
const DB = process.env.MONGO_URL.replace(`<PASSWORD>`,
process.env.PASSWORD);
mongoose
.connect(DB, {})
.then((con) => {
console.log(`DB is connected`);
})
.catch((err) => {
console.log(err);
});
const http = require("http");
const server = http.createServer(app);
const io = require("socket.io")(server);
io.on("connection", (socket) => {
console.log("A client connected");
socket.on("message", (message) => {
console.log("Received message:", message);
io.emit("message", message);
});
});
server.listen(PORT, () => {
console.log(`Aplikacija radi na portu broj ${PORT}`);
});
app.js file:
const express = require(`express`);
const app = express();
const userRouter = require(`../backend/routes/userRoutes`);
const chatRouter = require(`../backend/routes/ChatRoutes`);
const messageRouter = require(`../backend/routes/MessageRoutes`);
const cors = require(`cors`);
const bodyParser = require(`body-parser`);
//MIDLEWARE
app.use(bodyParser.json());
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && "body" in err)
{
res.status(400).json({ status: "failed", message: "Invalid JSON
payload" });
} else {
next();
}
});
app.use(
cors({
origin: "*",
credentials: true,
})
);
//ROUTES
app.use(`/`, userRouter);
app.use(`/chat`, chatRouter);
app.use(`/messages`, messageRouter);
module.exports = app;
Upvotes: 0
Views: 1298
Reputation: 165
in vercel.json
file you have to add
"installCommand": "npm install"
and remove ../backend
from src
after making changes the vercel.json
file looks like this
{
"version": 2,
"builds": [
{
"src": "./server.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/"
}
],
"installCommand": "npm install"
}
finally make sure your server is listening on some port(like 5000) that you have added in your env variable in vercel
Upvotes: 0