Home > Software design >  repost: Setting up express.js Server
repost: Setting up express.js Server

Time:12-19

Im encountering this error on replit while setting up my express server, im still starting to learn express so i still dont know some of it means

/home/runner/log-in-API/node_modules/express/lib/router/index.js:513
  this.stack.push(layer);
             ^

TypeError: Cannot read properties of undefined (reading 'push')
    at Function.route (/home/runner/log-in-API/node_modules/express/lib/router/index.js:513:14)
    at file:///home/runner/log-in-API/api/reviews.route.js:4:8
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)

here is my index.js

import app from "./server.js"
import mongodb from "mongodb"
/* import ReviewsDao from "./dao/reviewsDAO.js " */

const dbUser = process.env['MONGO_USERNAME']
const dbPword = process.env['MONGO_PASSWORD']

const MongoClient = mongodb.MongoClient
const uri = `SECRET`

const port = 8000

MongoClient.connect(uri, {
  maxPoolSize: 50,
  wtimeoutMS: 2500,
  useNewUrlParser: true
})
.catch(err => {
  console.error(err.stack)
  process.exit(1)
})
.then(async client => {
  await ReviewsDAO.injectDB(client)
  app.listen(port, () => {
    console.log(`Listening to ${port}`)
  })
})

here is my server.js

import express from "express"
import cors from "cors"
import reviews from "./api/reviews.route.js"

const app = express()

app.use(cors())
app.use(express.json())

app.use("/api/v1/reviews", reviews)
app.use("*", (req, res) => res.status(404).json({error: "not found"}))

export default app

and here is my reviews.route.js that is located inside a folder named api

import express from 'express'
const router = express.Router

router.route('/').get((req, res) => {
  res.send('Hello world')
})

export default router

Am i missing something im trying to follow this tutorial by free code camp and im currently at 6:16:30 timestamp

i tried to fix everything even typos, and im still encountering this problem what could be the problem ?

CodePudding user response:

I think this problem is created because the way you structure your router, try router.get('/', (req, res) => { instead of router.route('/').get((req, res) => {. Does this work? And to initialise your router try const router = express.Router(); instead of const router = express.Router (so call the factory function)

  • Related