forked from Trisha-tech/OnlineBookSales
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (70 loc) · 2.52 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const express = require("express");
const path = require("path");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const errorMiddleware = require("./middlewares/error.js");
// Load environment variables from .env file
dotenv.config({ path: ".env" });
const PORT = process.env.PORT || 8080;
console.log(process.env.MONGO_URL);
/* MONGODB CONNECTION START */
const MONGO_URL = process.env.MONGO_URL;
// CORS
const cors = require("cors");
app.use(
cors({
origin: "http://localhost:3000", // your frontend's origin
optionsSuccessStatus: 200,
origin: "http://localhost:3000", // Allow requests from localhost:3000
credentials: true, // Allow sending cookies from the frontend
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], // Allow the HTTP methods you use
allowedHeaders: ["Content-Type", "auth-token", "Origin", "X-Requested-With", "Accept"], // Allow headers
})
);
// Check if MONGO_URL is defined
if (!MONGO_URL) {
console.error("MONGO_URL is not defined in the environment variables.");
process.exit(1); // Terminate the application
}
// MongoDB connection
mongoose.connect(MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("connected", () => {
console.log("Connected to MongoDB");
});
mongoose.connection.on("error", (err) => {
console.log("Error Connecting to Database", err);
});
/* MONGODB CONNECTION END */
app.use(express.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
// Route Imports
const customer = require("./routes/customerRoutes.js");
const productRoutes = require("./routes/productRoutes.js");
const order = require("./routes/orderRoutes.js");
const admin = require("./routes/adminRoutes.js");
const wishlistRoutes = require("./routes/wishlistRoutes.js");
const { authorizeRoles } = require("./middlewares/auth.js");
app.use("/customer", customer);
app.use("/api/product", productRoutes);
app.use("/order", order);
app.use("/admin", authorizeRoles, admin);
app.use("/api/wishlist", wishlistRoutes);
app.use("admin", authorizeRoles, admin);
// Middleware for Errors
app.use(errorMiddleware);
app.get("/", (req, res) => {
res.send(`Welcome to Scizers Assignment !!! Made by Trisha Sahu`);
});
// New Route for Cart
const cartRoutes = require("./routes/cartRoutes.js");
app.use("/api/cart", cartRoutes);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});