简体   繁体   中英

Split express node js into two

I'm trying to split a code to two using express. Here is what it I did

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);

    })

};

When I'm trying to run it in my loclhost writing http://localhost:3000/getAllExcellenceStudent I get Cannot GET /getAllExcellenceStudent

What did I do wrong?

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

You have couple errors in your code.

1 - stud.excellence; and module.exports = function excellence() { in this case you should use it as var stud = require('./grades')(); or

var stud = require('./grades'); 
var excellence = new stud();

2 - It wouldn't work, cos grades.js have no idea about variable app . So, as solution, you could pass it as argument:

    module.exports = function excellence(app) {
        app.get('/getAllExcellenceStudent', function(req, res) {
            res.json(text);

        })

    };

//index.js

var stud = require('./grades')(app);

You can, but this is totally wrong approach. Mr. @bilalmetla gives correct answer, you should use express.Router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM