我正在尝试使用 Node.js 设置 REST api,但我想使用 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()
使用 require从方法初始化我的所有控制器。该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
我总是得到:
获取 /api/country 404 4.375 毫秒 - 150
它似乎无法识别路线。任何帮助找出我做错了什么?谢谢
我撤销我的回答。我不想再支持这个网站了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句