Как исправить «Route.get () требует функции обратного вызова, но получил [объект Undefined] на маршруте» в узле js? - PullRequest
0 голосов
/ 28 января 2019

Я получил Route.get() requires a callback function but got a [object Undefined] ошибка.

на route.js У меня есть следующий код:

const product_controller = require('../controllers/product.controller');
router.get('/test', product_controller.test);

На product.controller У меня есть следующий код:

module.exports = {test: function(req,res){res.send('Greetings from the Test controller!');},}

1 Ответ

0 голосов
/ 28 января 2019

Прекрасно работает на моей машине. XD.

const express= require('express');
var router= new express();
var path= require('path');

const product_controller = require('../controllers/product.controller');
router.get('/test', product_controller.test);

router.listen(3000, (err) => console.log("listening on port 3000"));

Возможно, вам следует проверить свои пути, а также выйти из системы product_controller.test, чтобы увидеть, не отображается ли она как функция или нет.

Я рекомендую использовать .use() для маршрутизации запросов к определенному файлу.Таким образом, вы можете сохранить всю логику, относящуюся к определенному маршруту, в одном файле.

var product_controller = require('./controllers/product.controller');
app.use('/test', product_controller);

Вот и все приложение.

Server.js

const express= require('express');
var app= new express();
var path= require('path');

var product_controller = require('./controllers/product.controller');
app.use('/test', product_controller);

app.listen(3000, (err) => console.log("listening on port 3000"));

product.controller.js

const express= require('express');
var router= new express();
var path= require('path');

router.get('/', function(req, res)
 {
    res.send('Greetings from the Test controller!');
 });

module.exports= router;

Структура файла выглядит следующим образом: ОСНОВНАЯ ПАПКА ПРИЛОЖЕНИЯ>

  • Узловые модули
  • controller> product.controller.js
  • server.js
  • package.json
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...