skip to Main Content

Trying to connect the API through Route is not responding , Getting the status error: "not connected"

restaurants.route.js
Integrated The Route Here

import express from "express"
const router = express.Router()
router.route('/api/v1/restaurants').get((req,res) => res.send("helloworld"))
export default router

index.js
Connect to MongoDB.

import mongodb from "mongodb"
import dotenv from "dotenv"
dotenv.config()
const MongoClient = mongodb.MongoClient

const port = process.env.PORT || 8000

MongoClient.connect(
    process.env.RESTREVIEWS_DB_URI,
    {
        maxPoolSize: 50,
        wtimeoutMS: 2500,
        useNewUrlParser: true,
    }
)
.catch(err =>{
    console.error(err.stack)
    process.exit(1)
})
.then(async client =>{
    App.listen(port,() =>{
        console.log(`listen on port ${port}`)
    })
}) 

server.js
Connect to the server

import  express  from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js"

const App = express()

App.use(cors())
App.use(express.json())

App.use("/api/v1/restaurants", restaurants)
App.use("*", (req, res) => res.status(404).json({error:"not connected"}))

export default App

2

Answers


  1. You should declare your route middleware as:

    App.use("/", restaurants)
    

    Otherwise, you will initialize the end-point as /api/v1/restaurants/api/v1/restaurants.

    Login or Signup to reply.
  2. Change App.use("/api/v1/restaurants", restaurants) to App.use("/api/v1", restaurants) and router.route('/api/v1/restaurants') to router.route('/'). From then you can call to /api/v1/restaurants and get the expected result

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search