0
// Require packages and set the port
const express = require('express');
const port = 3002;
const app = express();

const bodyParser = require('body-parser');

const routes = require('./routes/routes');

// Use Node.js body parsing middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true,
}));

app.get('/', (request, response) => {
    console.log(`URL: ${request.url}`);
    response.send({
        message: 'Grades'}
        );
});

// Start the server
const server = app.listen(port, (error) => {
    if (error) return console.log(`Error: ${error}`);

    console.log(`Server listening on port ${server.address().port}`);
});

// Export the router
module.exports = router;

I'm setting up a new route and got some issue with code. It's my first post here, and I'm starting with programming, so it would be great if you show some understanding. :) I suppose that mistake is in the line with app.get where I have to put also routes(app);, but unfortunately, I don't know how to use it. There might be a problem with the last line, I might just use it in the wrong way.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
jarmol
  • 5
  • 1
  • 1
  • 2
  • You never define `router`. I'm not sure what you expect it to be. – VLAZ Aug 27 '19 at 12:44
  • How to use it and where do I have to put it? – jarmol Aug 27 '19 at 12:47
  • 1
    I think this is your root index file. you don't have to export anything from here until and unless you are going to require this file in other files. you can remove module.exports = router line, it will work then. – A. Todkar Aug 27 '19 at 12:48
  • It works! Thank you very much! I really appreciate it. – jarmol Aug 27 '19 at 12:53

1 Answers1

1

There are two ways to define your routes in express. One is to use express app instance and other is to using express router. And you are mixing them both.

The way you have defined your routes is correct. Remove const routes = require('./routes/routes'); && module.exports = router; from your code and it will work fine.

Or else if you wanna keep the routes in separate files using router, Have a look at this.

Hope this helps :)

Mohammed Amir Ansari
  • 2,311
  • 2
  • 12
  • 26