Reputation: 5
// 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.
Upvotes: 0
Views: 23233
Reputation: 2401
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 :)
Upvotes: 1