当前位置: 首页 > 知识库问答 >
问题:

错误:Route.get()需要一个回调函数,但在app.js处得到了一个[object Undefined]

查锦程
2023-03-14

我不知道为什么会出现这个错误,我有另一个模型和几乎相同的路由和控制器,但没有工作,这是消息:error:route.get()需要一个回调函数,但得到了一个[对象未定义]在路由。[as get](/users/ediechavero/documents/recipe-api/node_modules/express/lib/router/route.js:202:15),位于function.proto。[as get](/users/ediechavero/documents/recipe-api/node_modules/express/lib/router/index.js:510:19)。(/users/ediechavero/documents/recipe-api/routes/places-routes.js:22:8)在module._compile(internal/modules/cjs/loader.js:115630)在object.module._extensions.js(internal/modules/cjs/loader.js:1176:10)在module.load(internal/modules/cjs/loader.js:1000:32)在function.module._load((/users/ediechavero/documents/recipe-api/app.js:62:15),位于object.module._extensions..js的module._compile(internal/modules/cjs/loader.js:1156:30

//Controllers places this is the controllers file for the crud places
const Place = require('../models/Place');

exports.getAllPlacess = async (req, res) => {
  try {
    const places = await Place.find().populate('owner');
    res.status(200).json({ places });
  } catch (error) {
    res.status(400).json({ message: `${error}` });
  }
};

exports.getPlace = async (req, res) => {
  try {
    const { id } = req.params;
    const place = await (await Place.findById(id)).populate('owner');
    res.status(200).json({ place });
  } catch (error) {
    res.status(400).json({ message: `${error}` });
  }
};

exports.createPlace = async (req, res) => {
  try {
    const { name, typePlace, address } = req.body;
    const owner = req.user.id;

    const place = await Place.create({
      name,
      typePlace,
      address,
      owner,
    });
    res.status(201).json({ place });
  } catch (error) {
    res.status(400).json({ message: `${error}` });
  }
};

exports.updatePlace = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, typePlace, address } = req.body;
    const place = await Place.findByIdAndUpdate(id, {
      name,
      typePlace,
      address,
      owner,
    });
    res.status(200).json({ place });
  } catch (error) {
    res.status(400).json({ message: `${error}` });
  }
};

exports.deletePlace = async (req, res) => {
  try {
    const { id } = req.params;
    await Place.findByIdAndDelete(id);
    res.status(200).json({ message: 'Deleted Recipe' });
  } catch (error) {
    res.status(400).json({ message: `${error}` });
  }
};



//Route this the file for the routes 
const express = require('express');
const router = express.Router();
const uploadConfig = require('../config/cloudinary');

const {
  getAllPlaces,
  getPlace,
  createPlace,
  updatePlace,
  deletePlace,
} = require('../controllers/places');

router.post('/upload', uploadConfig.single('photo'), (req, res, next) => {
  if (!req.file) {
    next(new Error('No file uploades'));
  }
  res.status(201).json({ secure_url: req.file.secure_url });
});

//CRUD PLACES

router.get('/places', getAllPlaces);
router.get('/places/:id', getPlace);
router.post('/places/create', createPlace);
router.put('/places/edit/:id', updatePlace);
router.delete('/places/delete/:id', deletePlace);

module.exports = router;

//app.js

require('dotenv').config();

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const path = require('path');
const colors = require('colors');
const cors = require('cors');
const session = require('express-session');

mongoose
  .connect(process.env.DB, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then((x) =>
    console.log(
      `Connected to Mongo! Database name: "${x.connections[0].name}"`.cyan
        .underline.bold
    )
  )
  .catch((err) => console.error('Error connecting to mongo', err.red));

const app_name = require('./package.json').name;
const debug = require('debug')(
  `${app_name}:${path.basename(__filename).split('.')[0]}`
);

const app = express();

app.use(
  cors({
    credentials: true,
    origin: [process.env.FRONTENDPOINT],
  })
);

app.use(
  session({
    resave: false,
    saveUninitialized: true,
    secret: process.env.SECRET,
    cookie: { maxAge: 1000 * 60 * 60 },
  })
);

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(logger('dev'));

const index = require('./routes/index');
app.use('/', index);

const recipe = require('./routes/recipe-routes');
app.use('/api', recipe);

const place = require('./routes/places-routes');
app.use('/api', place);

// Uncomment this line for production
// app.get('/*', (req, res) => res.sendFile(__dirname + '/public/index.html'));

module.exports = app;

共有1个答案

颜君浩
2023-03-14

它看起来有一个拼写不同的地方,你导出和你导入。

您正在将一个导出定义为:

exports.getAllPlacess = function() { ... }

但是,然后将其导入为:

const {
  getAllPlaces,
  getPlace,
  createPlace,
  updatePlace,
  deletePlace,
} = require('../controllers/places');

更改此内容:

exports.getAllPlacess = function() { ... }

对此:

exports.getAllPlaces = function() { ... }
 类似资料: