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
You should declare your route middleware as:
Otherwise, you will initialize the end-point as
/api/v1/restaurants/api/v1/restaurants
.Change
App.use("/api/v1/restaurants", restaurants)
toApp.use("/api/v1", restaurants)
androuter.route('/api/v1/restaurants')
torouter.route('/')
. From then you can call to/api/v1/restaurants
and get the expected result