How to configure express router along with ES6?

17,759

Solution 1

Your api is currently set to /api/api/devices/:id. Remove the /api from the router get definition:

router                  
    .get('/devices/:id',function (req, res) { 

Solution 2

Can also be resolved by skipping the mount param:

import api from './routes';
app.use(api);
Share:
17,759
Bazinga777
Author by

Bazinga777

Still a learner and improving. maisnamraju.in SOreadytohelp

Updated on June 11, 2022

Comments

  • Bazinga777
    Bazinga777 almost 2 years

    I have the following code for an router file in express.

    import express from 'express';
    import  _  from 'lodash';
    import { Devices, OwlElecMonitors } from '../models/';
    
    var router = express.Router();
    
    router.get('/api/devices/:id',function (req, res) {
        console.log(req);                   
        Devices.getDevicesByUserId({ userId: req.params.id },function(err, resp) {
            res.send(resp);
        });
    });
    
    export default router;
    

    and I am trying to import it into the main file using the following code

    import api from './routes';
    app.use('/api', api);
    

    But the code returns a 404 error. Where am I going wrong ? What changes do I need to make for this to work ?

  • Bazinga777
    Bazinga777 over 8 years
    Thanks, that was the issue.
  • Insanovation
    Insanovation about 3 years
    That actually worked for me. Interesting, if I provide the mount param - it will break and return "Cannot GET /foo"... Why?
  • Insanovation
    Insanovation about 3 years
    Ah, found it: // use the router and 401 anything falling through app.use('/admin', router, function (req, res) { res.sendStatus(401) }) At: expressjs.com/en/guide/using-middleware.html