Ошибка: Route.get () требует функцию обратного вызова, но получил [объект Undefined] - PullRequest
0 голосов
/ 10 мая 2018

Я пытаюсь создать приложение поиска рецептов, используя Express в качестве бэкэнда, и получаю сообщение об ошибке в заголовке из файла моего маршрутизатора при запуске сервера. Ранее я делал проекты, в которых мой маршрутизатор следовал так же, как и здесь, но по какой-то причине я продолжаю получать ошибку и не могу понять, почему. Ниже я вставил код в мои файлы контроллера, помощника и маршрута:

Контроллер:

// import model and users controller
const Recipe = require('../models/recipe');
const usersController = require('../controllers/users-controller');

// initiate controller object
const recipesController = {}

// send API data
recipesController.sendApiRecipe = (req, res) => {
    res.json({
        message: `recipe returned`,
        recipe: res.locals.recipe,
    })
}

// show all favorited recipes
recipesController.index = (req, res, next) => {
    Recipe.findByUser(req.user.id)
    .then(recipe => {
        res.json({
            message: 'rendering favorites',
            data: { recipe },
        })
    }).catch(next)
}

// create favorite recipe
recipesController.create = (req, res) => {
    console.log(req.body, 'from create/recipesController')
    Recipe.create({
        title: req.body.title,
        diet: req.body.diet,
        calories: req.body.calories,
        servings: req.body.servings,
        health: req.body.health,
        ingredient: req.body.ingredient,
        img: req.body.img,
        link: req.body.link,        
        user_id: req.user.id,
    }).then(recipe => {
        res.json({
            message: 'successfully added',
            data: { recipe }
        })
    }).catch(err => {
        console.log(err)
        res.status(500).json({error: err})
    })
}

// delete favorite recipe
recipesController.delete = (req, res, next) => {
    Recipe.destroy(req.params.id)
    .then(() => {
        res.json({
            message: 'successfully deleted recipe',
        })
    }).catch(next)
}

export default recipesController;

Помощник:

// import dependencies
require('isomorphic-fetch')
require('dotenv').config()

function getRecipes(req, res, next) {
    // fetch URL
    fetch(`https://api.edamam.com/search?q=${req.params.search}&app_id=${process.env.APP_ID}&app_key=${process.env.APP_KEY}&from=0&to=30`)
    .then(res => res.json())
    // use res.locals to attach data to repsonse object
    .then(fetchRes => {
        // set fetched results to res.locals
        res.locals.recipe = fetchRes
        next()
    })
}

// export function
module.exports = {
    getRecipes: getRecipes,
}

Маршруты:

// import dependencies
const express = require('express')
const recipeHelpers = require('../services/recipes/recipe-helpers')
const recipesController = require('../controllers/recipes-controller')

const recipesRouter = express.Router()

recipesRouter.get('/:search', recipeHelpers.getRecipes, recipesController.sendApiRecipe)
recipesRouter.post('/create', recipesController.create)

module.exports = recipesRouter;

Пожалуйста, дайте мне знать, если есть какая-либо дополнительная информация, которую я должен предоставить, и я обязательно свяжусь с любыми выводами, с которыми я столкнусь, когда буду устранять неполадки. Заранее спасибо за любую помощь!

1 Ответ

0 голосов
/ 10 мая 2018

Я только что понял, что неправильно экспортировал свой контроллер, и исправление, которое решило проблему. Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...