Поиск маршрута в узле js rest api с классами Express и ES6
Я пытаюсь настроить REST API с Node.js, но я хочу сделать это с помощью классов ES6, мой app.js выглядит так:
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
class ApplicationServer {
constructor() {
this.app = express();
this.initExpress();
this.initExpressMiddleWare();
this.initControllers();
this.start();
}
initExpress() {
this.app.set('port', process.env.PORT || 3000);
}
initExpressMiddleWare() {
this.app.use(morgan("dev"));
this.app.use(bodyParser.json());
}
initControllers() {
require('./controllers/CountryController')(this.app);
}
start() {
this.app.listen(this.app.get('port'), () =>{
console.log(`Server listening for port: ${this.app.get('port')}`);
});
}
}
new ApplicationServer();
Все работает нормально, сервер запускается и прослушивает порт 3000, никаких проблем, но если вы видите, я пытаюсь инициализировать все свои контроллеры с initControllers()
метод использования требуют. CountryController.js
Файл содержит класс со следующим кодом:
class CountryController {
contructor(app) {
this.app = app;
this.getCountries();
}
getCountries() {
this.app.get('api/country', (req, res) => {
res.json([]);
});
}
}
module.exports = ( app ) => { return new CountryController( app ) }
После этого я не получил ошибку при запуске сервера, но при попытке вызвать метод API localhost:3000/api/country
Я всегда получаю:
GET / API / страна 404 4,375 мс - 150
Кажется, что он не признает маршрут. Любая помощь, чтобы найти то, что я делаю не так? Спасибо
1 ответ
Решение
Вы пробовали использовать маршрут с косой чертой, предшествующей маршруту?
Попробуйте изменить свой маршрут с
api/country
в
/api/country