错误:Route.get()需要一个回调函数但得到一个[对象未定义]

时间:2018-05-10 02:00:15

标签: node.js express

我正在尝试使用Express作为我的后端创建一个配方搜索应用程序,当我启动服务器时,我从我的Router文件中获取标题中的错误消息。我之前做过项目,我的路由器遵循与此处相同的方式,但由于某种原因我不断得到错误,我无法弄清楚原因。下面我将代码粘贴到我的控制器,帮助器和路径文件中:

控制器:

// 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 :(得分:0)

我刚刚意识到我没有正确导出我的控制器,修复它解决了这个问题。谢谢!