My package.json file is
{
“name”: “mern”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“type”: “module”,
“scripts”: {
“dev”: “nodemon api/index.js”,
“start”: “node api/index.js”,
“build”: “npm install && npm install --prefix client && npm run build --prefix client”
},
“keywords”: ,
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“bcryptjs”: “^2.4.3”,
“cookie-parser”: “^1.4.6”,
“dotenv”: “^16.4.5”,
“express”: “^4.18.2”,
“jsonwebtoken”: “^9.0.2”,
“mongoose”: “^8.2.0”,
“nodemon”: “^3.0.3”
}
}
and index.js file
import express from ‘express’;
import mongoose from ‘mongoose’;
import dotenv from ‘dotenv’;
import userRouter from ‘./routes/user.route.js’;
import authRouter from ‘./routes/auth.route.js’;
import listingRouter from ‘./routes/listing.route.js’;
import cookieParser from ‘cookie-parser’;
import path from ‘path’;
dotenv.config();
mongoose.connect(process.env.MONGO).then(() => {
console.log(‘connected to mongoDB’);
}).catch((err) => {
console.log(err);
});
const __dirname = path.resolve();
const app = express();
app.use(express.json());
app.use(cookieParser());
app.listen(3000, () => {
console.log(‘Server is running on port 3000!’);
});
app.use(“/api/user”, userRouter);
app.use(“/api/auth”, authRouter);
app.use(‘/api/listing’, listingRouter);
app.use(express.static(path.join(__dirname, ‘/client/dist’)));
app.get(‘*’, (req, res) => {
res.sendFile(path.join(__dirname, ‘client’, ‘dist’, ‘index.html’));
})
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
const message = err.message || ‘Internal Server Error’;
return res.status(statusCode).json({
success: false,
statusCode,
message,
});
});