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 ?
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
I am trying to set up a few pages so that when a user goes to locahost:number/war . They can see the /war page. But when I run the server I get a "Cannot GET war" error on the page. I've set it up similar to this before and didnt have an issue.
I also get a "ReferenceError: __dirname is not defined" issue on the console
import express from 'express';
const app = express();
const router = express.Router();
import path from 'path';
import {getData} from './server.js'
// HTML Routes
router.get('/', (req,res)=> {
res.sendFile(path.join(__dirname, "../start.html"));
})
router.get('/war', (req,res)=> {
res.sendFile(path.join(__dirname, "../index.html"));
})
router.get('/score', (req,res)=> {
res.sendFile(path.join(__dirname, "../finalScore.html"));
})
// Data
export async function sendStats(){
app.get("/data", (req,res)=> {
const data = getData()
res.json(data)
})
app.post("/data",(req, res) => {
const {name, score} = req.body
const data = createData(name, score)
res.json(data)
} )
app.use((err, req, res, next) => {
console.log(err.stack)
res.status(500).send('Something Broke!')
})
app.listen(7171, ()=> {
console.log('Server is running on port 9191')
})
}
const data = await sendStats();
You forgot to load the router in the app:
app.use('/', router)
I am following a tutorial in order to understand how to connect the express routes that I have written to a react app.
The code, as I best understand it, is supposed to work as follows
App.js
import axios from "axios"
import React, { useState } from "react"
import "./App.css"
function App() {
const [ name, setName ] = useState("")
const [ home, setHome ] = useState("")
useEffect(() => {
axios.get("http://localhost:4000/home").then(function(response) {
setHome(response.data)
})
}, [])
async function postName(e) {
e.preventDefault()
try {
await axios.post("http://localhost:4000/post_name", {
name
})
} catch (error) {
console.error(error)
}
}
return (
<div className="App">
<form onSubmit={postName}>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Send Name</button>
</form>
{home}
</div>
)
}
export default App
the body above has a submit form that takes text inputted by the user, then on submit the form calls the async function postName. postName utilizes the built in function axios.post which fetches the url corresponding to the url/express_route my index.js is using and passes in the object name which I created at the top of the function in my useState.
In the index.js
const express = require("express")
const app = express()
const port = 4000
const cors = require("cors")
// npm init
// npm i express cors nodemon
// they add a handy req.body object to our req,
// containing a Javascript
// object representing the payload sent with the request
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())
app.get("/", cors(), async (req, res) => {
res.send("This is working")
})
app.get("/home", cors(), async (req, res) => {
res.send("This is the data for the home page")
})
app.post("/post_name", async (req, res) => {
let { name } = req.body
console.log(name)
})
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
})
we have an async function app.post which is meant to deal with the express route we set up in the axios function and then prints the submitted name to console. I am able to get both of them running. I have nodemon, express axios and cors installed to allow for communication between the different urls. What am I missing why is this happening.
I have index.js file like this and
const express = require('express');
const app = express();
//Import Routes
const authRoute = require('./routes/auth');
//Route Middlewares
app.use('/api/user', authRoute);
app.listen(3000, () => console.log('Server Up and running'));
auth.js like this one
const router = require('express').Router();
router.post('/register', (req, res) => {
res.send('Register');
})
module.exports = router;
Why i get the TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\router\index.js:458:13)
at Function. (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\application.js:220:21)
You may try to re-write your auth.js in the following format, I think that will solve the issue:
router.route('/register').post((req, res) => { .............
Hi I am trying to export both a function (so that other routes may use this function to verify certs and also a the express router so that I can add it to my main class to mount the route on. This is because I believe the function and the route both serve the same sort of "functionality" and I want to encapsulate it in one file, so I want to export both the function and the router to use! Here is the following code of which I get an error... Note I WANT to do verifytoken.router to refer to the router and then verifytoken.verify to refer to the function in other files
/routes/verifytoken.js file
const router = require('express').Router();
const jwt = require('jsonwebtoken');
function verify (req, res, next) {
const token = req.header("auth-token");
if (!token) return res.status(401).send("Access Denied");
try {
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = verified;
next();
} catch (error) {
res.status(400).send("Invalid Token")
}
}
router.get("/tester", (req, res) => {
res.status(200).send("validation please work bro");
});
module.exports = {
verify:verify,
router:router
}
my main index.js file
const express = require('express');
//import routes
const verifytoken = require('./routes/verifytoken')
const app = express();
//route middlewares
app.use("/api/user". verifytoken.router);
app.listen(3000 , () => console.log('Server Running...'))
The stack trace is :
app.use("/api/user". verifytoken.router);
^
TypeError: Cannot read property 'router' of undefined
1) Another typo:
app.use("/api/user". verifytoken.router);
Should be: (note dot . instead of comma ,)
app.use("/api/user", verifytoken.router);
2) You're using the wrong filename in the imported module:
const verifytoken = require('./routes/verifytoken');
Should be:
const verifytoken = require('./routes/verify');
The required file is named verify.js not verifytoken.js
I think there's another typo (dot), try:
app.use("/api/user", verifytoken.router);
I am using a NextJS/MERN stack. My NextJS is using my server.js file, along with importing the routes for my API. The routes appear to be working as they do show activity when firing an API call from Postman or the browser. However, this is where the activity stops. It's not getting passed the Model.find() function as far as I can tell. I am not sure if this has to do with Next js and the prepare method in the server.js, or if this is related to the bodyparser issue.
Here is my server.js
const express = require("express");
const urlObject = require('./baseURL')
const passport = require("./nextexpress/config/passport-setup");
const passportSetup = require("./nextexpress/config/passport-setup");
const session = require("express-session");
const authRoutes = require("./nextexpress/routes/auth-routes");
const KBRoutes = require("./nextexpress/routes/kb-routes");
const userRoutes = require('./nextexpress/routes/user-routes')
const pollRoutes = require('./nextexpress/routes/poll-routes')
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser"); // parse cookie header
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const nextapp = next({ dev })
const handle = nextapp.getRequestHandler()
const bodyParser = require('body-parser');
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/kb', { useNewUrlParser: true });
mongoose.connect('mongodb://localhost:27017/kb')
console.log(process.env.MONGODB_URI)
const connection = mongoose.connection;
const baseURL = urlObject.baseURL
const PORT = process.env.PORT || 3000
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
})
nextapp.prepare().then(() => {
const app = express();
console.log(process.env.PORT, '----port here ----')
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/api/auth", authRoutes);
app.use("/api/kb", KBRoutes);
app.use('/api/user', userRoutes)
app.use('/api/poll', pollRoutes)
app.get('/posts/:id', (req, res) => {
return nextapp.render(req, res, '/article', { id: req.params.id })
})
app.get('/redirect/:id', (req, res) => {
return nextapp.render(req, res, '/redirect')
})
app.all('*', (req, res) => {
return handle(req, res)
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
// connect react to nodejs express server
And the relevant route:
KBRoutes.get('/', (req, res) => {
console.log(KB.Model)
KB.find({}, (err, photos) => {
res.json(kbs)
})
})
I am able to get to each one of the routes. Before this was working, when I had the NextJS React portion split into a separate domain therefore separate server.js files. Once I introduced NextJs thats when this problem arose. Any help would be greatly appreciated.
It looks like the relevant route is trying to return json(kbs), but kbs doesn't seem to be defined. Returning the result of your find query would make more sense to me, including a nice error catcher and some status for good practice. Catching errors should tell you what's going wrong, i would expect an error in your console anyway that would help us out finding the answer even more.
KB.find({}, (err, photos) => {
if (err) res.status(401).send(err)
res.status(200).json(photos)
})