简体   繁体   中英

Node: Route.get() requires a callback function but got a [object Undefined]

Im trying to create a simple CRUD app in node js and i get Route.get() requires a callback function but got a [object Undefined] on the router.get("/:id", userController.getUser); line

Routes.js

const express = require('express')
const userController= require('../controllers/userController.js')

const router = express.Router()

/* READ */
router.get("/:id", userController.getUser);

module.exports = router

Controller.js

const getUser = async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.findById(id);
    res.status(200).json(user);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
}

const Function..

const AnotherFunction..


module.exports = {
   getUser,
   Function,
  AnotherFunction,
}


console.log(userController.getUser.toString()) prints:

async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.findById(id);
    res.status(200).json(user);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
}

I don't have correct access rights to push into your repo so explaining the issue here.

In your auth.js you have exported verifyToken function as default export.

module.exports = verifyToken .

But you are destructuring when importing in postsController.js

const {verifyToken} = require ('../middleware/auth.js')

Importing like this will get the correct function =>

const verifyToken = require("../middleware/auth.js");

Change your postsController file as below. It should work.

const express = require("express");
const verifyToken = require("../middleware/auth.js");
module.exports = verifyToken;

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