cannot GET / express.js routing

Viewed 7194

I am at the early stages of a simple tasks manager that I want to build with the MEAN Stack. I can figure/resolve a simple routing issue. I don't see any error message in the terminal or console except for the 404 client error.

the root path is ok. I get a response back I use html docs to render the ui for both.

this is how I have set up my server.js

var express = require('express')
var path = require('path')
var bodyParser = require('body-parser')

var index = require('./routes/index');
var tasks = require('./routes/tasks');
var app = express();

const port = '3456'


app.use('/', index)
app.use('api', tasks) <= HERE

//view engine
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.engine('html', require('ejs').renderFile);

//static folder
app.use(express.static(path.join(__dirname, 'client')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))



app.listen(port, function() {
    console.log('Starting the server at port'  + port );
})

tasks.js

to render the template at the set route

var express = require('express')
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://sandy:cookie2080@ds147304.mlab.com:47304/tasklists_21092017', ['tasks'])

router.get('/tasks', function(req, res, next) {
    res.send('api')
    res.render('tasks.html')
    db.tasks.find(function(err, tasks){
        if (err) {
            res.send('error message ' + err)
        }

        res.json(tasks)
    })
})

module.exports = router;

and, index.js fyi

var express = require('express')
var router = express.Router();

router.get('/', function(req, res, next) {
    res.render('index.html')
})

module.exports = router;

screenshot at the link below of the 404 error in browser after starting server on port 3456

404 error - screenshot

thanks for the help. I am sure it can be a little detail. it is very hard to debug though.

2 Answers

This error occurs because there's no route that handles the endpoint /api. What you can do here is create a middleware that will handle the /api. You can do it in your tasks.js like this:

tasks.js

router.get('/', function(req, res, next) {
   res.send('This is api.')
})

Or if what you want to do is to direct the user from the endpoint /api to /api/tasks then you could do it like this:

router.get('/', function(req, res, next) {
   res.redirect('/api/tasks')
})

Hope this helps.

I changed the port number. The issue was that the port 3000, was not responding to the requests, as it was still in use by an older process hence producing the warning

errno: 'EADDRINUSE',.

Just used the port 5000 to try out and it went through smoothly.

By the way I am using vs code.

Related