简体   繁体   中英

TypeError: Cannot read property 'use' of undefined Express

I'm facing some issues with my express server when I use the 'app.use' command

in my task-routes.js file, I have the following code

import express from 'express';
const router = express.Router();


router.post('/task',(req, res) => {
    res.send('post.task - create a task');
});
router.get('/task',(req, res) => {
    res.send('get.task - get all tasks')
});
router.get('/task/:id',(req, res) => {
    res.send('get.task/:id - get task by id')
});
router.put('/task',(req, res) => {
    res.send('put.task - update a task')
});
router.delete('/task',(req, res) => {
    res.send('delete.task - delete a task')
});

export default router;

And in my routes.js file, I have this

import taskRoutes from './api/task/tasks-routes';

export function registerRoutes(app) {
app.use('/api',taskRoutes);

}

Index.js

import express from 'express';
const app = express()
import {registerRoutes} from './routes';
const port = 3000
registerRoutes();
app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`MEVN app listening at http://localhost:${port}`))

This is the error I keep getting

/Users/musabhamid/Desktop/mevn-stack copy/prod-server/routes.js:15
  app.use('/api', _tasksRoutes2.default);
      ^

TypeError: Cannot read property 'use' of undefined
    at registerRoutes (/Users/musabhamid/Desktop/mevn-stack copy/prod-server/routes.js:15:7)
    at Object.<anonymous> (/Users/musabhamid/Desktop/mevn-stack copy/prod-server/index.js:14:28)

You are missing to pass app as argument at Index.js

import express from 'express';
const app = express()
import {registerRoutes} from './routes';
const port = 3000
registerRoutes(app); // <- Here
app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`MEVN app listening at http://localhost:${port}`))
 app.use('/api',taskRoutes);

So you call app.use

What is app ?

 export function registerRoutes(app) {

It is the first argument you pass to registerRoutes .

So what is that?

 registerRoutes();

There isn't one. You didn't pass it an argument.


You have to pass the express object as the argument when you call the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM