Search code examples
javascriptnode.jsmongodbapiexpress

Server 404 NodeJs


I created a server and connected it with MongoDB when I made an API in the index.js File, it is coming, but when I created an function for the same and made an API in another file and exported to index.js Its coming 404 server error

This is my index.js file

import express from "express";
import Connection from "../backend/connection.js";
import dotenv from "dotenv";
import calling from "./data/routes/route.js";

dotenv.config();
const USERNAME = process.env.DB_USERNAME;
const PASSWORD = process.env.DB_PASSWORD;

const PORT = 5000;
const app = express();
app.listen(PORT, () => {
  console.log(`Server Started on Port ${PORT}`);
});

Connection(USERNAME, PASSWORD);

calling();

This is my route.js file

import express from "express";

const app = express();

const calling = () => {
  app.get("/blogs", (req, res) => {
    res.send("Yes");
  });
};

export default calling;

Here is the pic of the error

enter image description here

Tried to surf in google but not found anything


Solution

  • You are using two different app objects one in your route and one in index.js file

    Try the below answer instead if you want to keep things this way otherwise see this

    import express from "express";
    import Connection from "../backend/connection.js";
    import dotenv from "dotenv";
    import calling from "./data/routes/route.js";
    
    dotenv.config();
    const USERNAME = process.env.DB_USERNAME;
    const PASSWORD = process.env.DB_PASSWORD;
    
    const PORT = 5000;
    const app = express();
    app.listen(PORT, () => {
      console.log(`Server Started on Port ${PORT}`);
    });
    
    Connection(USERNAME, PASSWORD);
    
    calling(app);
    

    Your route.js file

    const calling = (app) => { // app object passed as an argument from the index.js
      // register all your routes here ,its the same app object that is used to start the server
    
      app.get("/blogs", (req, res) => {
        res.send("Yes");
      });
    };
    
    export default calling