我尝试使用express将代码拆分为两个。 这就是我做的事情
app.js
var express = require('express');
var app = express();
var stud = require('./grades');
var port = process.env.PORT || 3000;
stud.excellence;
app.listen(port);
grades.js
var text = '{ "students" : [' +
'{ "name":"Elsa" , "grade":"70" , "course":"ws" , "year":"2015" },' +
'{ "name":"Anna" , "grade":"80" , "course":"ws" , "year":"2016" },' +
'{ "name":"Anna" , "grade":"86" , "course":"math" , "year":"2014" },' +
'{ "name":"Ron" , "grade":"92" , "course":"math" , "year":"2016" } ]}';
module.exports = function excellence() {
app.get('/getAllExcellenceStudent', function(req, res) {
res.json(text);
})
};
当我试图在我的loclhost中编写http://localhost:3000/getAllExcellenceStudent时,我得到了无法获取/ getAllExcellenceStudent
我做错了什么?
答案 0 :(得分:0)
Your app.js should be like this. Actually you are missing app.use() to define routes
var express = require('express');
var app = express();
var stud = require('./grades');
var port = process.env.PORT || 3000;
app.use('/students', stud);
app.listen(port);
Your grades.js file should be like this.
var express = require('express');
var router = express.Router();
var text = '{ "students" : [' +
'{ "name":"Elsa" , "grade":"70" , "course":"ws" , "year":"2015" },' +
'{ "name":"Anna" , "grade":"80" , "course":"ws" , "year":"2016" },' +
'{ "name":"Anna" , "grade":"86" , "course":"math" , "year":"2014" },' +
'{ "name":"Ron" , "grade":"92" , "course":"math" , "year":"2016" } ]}';
router.get('/getAllExcellenceStudent', function(req, res) {
res.json(text);
});
module.exports = router;
Now you can access it using this route http://localhost:3000/students/getAllExcellenceStudent
答案 1 :(得分:0)
您的代码中有几处错误。
1 - stud.excellence;
和module.exports = function excellence() {
在这种情况下,您应该将其用作var stud = require('./grades')();
或
var stud = require('./grades');
var excellence = new stud();
2 - 它不起作用,cos grade.js不知道变量app
。因此,作为解决方案,您可以将其作为参数传递:
module.exports = function excellence(app) {
app.get('/getAllExcellenceStudent', function(req, res) {
res.json(text);
})
};
//index.js
var stud = require('./grades')(app);
你可以,但这是完全错误的做法。 @bilalmetla先生给出正确的答案,你应该使用express.Router。