Create a Connection in Node js and make an API

server.js

import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import dotenv from 'dotenv';
import router from "./routes/index.js";
import cors from "cors";

dotenv.config();

const app = express();

app.use(cors({
    origin: '*',
}))
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/media', express.static('media'));

mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => {
    console.log('Connected to MongoDB');
}).catch((error) => {
    console.error('MongoDB connection error:', error);
});

app.use('/api', router);
app.get('/', (req, res) => {
    res.send('Hello, API!');
});

const PORT = process.env.PORT;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});







Comments

Popular posts from this blog

React JS | Store form data in localStorage

React Redux Toolkit