首页 > 解决方案 > Route.get() 需要 API 的回调函数问题

问题描述

我正在尝试为我拥有的项目创建一个 API。

我遇到了这个错误,我不知道该怎么做。

throw new Error(msg);
    ^

Error: Route.get() requires a callback function but got a [object Undefined]
    at Route.<computed> [as get] (C:\Users\dunka\Documents\GitHub\weatherapp\server\node_modules\express\lib\router\route.js:202:15)
    at Function.proto.<computed> [as get] (C:\Users\dunka\Documents\GitHub\weatherapp\server\node_modules\express\lib\router\index.js:510:19)
    at module.exports (C:\Users\dunka\Documents\GitHub\weatherapp\server\app\routes\weather.routes.js:13:12)
    at Object.<anonymous> (C:\Users\dunka\Documents\GitHub\weatherapp\server\server.js:24:39)

我相信这与我的查找路线有关,但我不确定。我将附上一些代码示例。

天气.routes.js

module.exports = app => {
    const weather = require("../controllers/weather.controllers.js");
  
    var router = require("express").Router();
  
    // Create a new Tutorial
    router.post("/lookup", weather.check);
  
    // Retrieve all weather
    router.get("/", weather.findAll);
  
    app.use('/api/weather', router);
  };

数据.js

import http from "../http-common";

class WeatherService {
  getAll() {
    return http.get("/weather");
  }

  get(id) {
    return http.get(`/weather/${id}`);
  }

  create(data) {
    return http.post("/weather", data);
  }

  check(data) {
    return http.post("/lookup", data)
  }
  
  update(id, data) {
    return http.put(`/weather/${id}`, data);
  }

  delete(id) {
    return http.delete(`/weather/${id}`);
  }

  deleteAll() {
    return http.delete(`/weather`);
  }

  findByTitle(title) {
    return http.get(`/weather?title=${title}`);
  }
}

export default new WeatherService();

天气控制器.js

const db = require("../models");
const Weather = db.weather;
const Op = db.Sequelize.Op;
var functions = require('./functions');


//Check Weather

exports.check = (req, res) => {
    let city = req.body.city.toLowerCase();
    let values = functions.getData(city);

    WebAuthnAssertion.

    res.send(values);
    console.log(`It's ${values[0]} degrees in ${values[1]}!`);
};



// Find all published Tutorials
exports.findAllPublished = (req, res) => {
  
};

我正在关注本教程:

https://bezkoder.com/node-js-express-sequelize-mysql/

有人可以让我知道我做错了什么吗?

编辑

console.log(天气) 返回

{
  create: [Function],
  check: [Function],
  findOne: [Function],
  update: [Function],
  delete: [Function],
  deleteAll: [Function]
}

标签: node.jsexpresshttproutessequelize.js

解决方案


您没有findAll从控制器中导出中间件。findAllPublished在您的控制器中重命名为:

exports.findAll = (req, res) => {
  // impl here
};

或使用以下方法设置路由器:

router.get("/", weather.findAllPublished);

推荐阅读