ujjwal singh
ujjwal singh

Reputation: 90

Node Js express router not working

js and i am learning node js along with express and I was learning express routing I have following code in rest.js

    const http = require('http');
const express = require('express');
const widgetRouter = require('./rest/widgets');

const app1 = express(); 

const server = http.createServer(app1);



app1.get('/api',widgetRouter);


server.listen(3000,function(){
    console.log('server started in port 3000');

});



const app = express();

and I also have widgets.js file

const express = require('express');

const widgetRouter = express.Router();

widgetRouter.route("/widgets")
    .get(function(req,res){
        res.json({"abc":"hello"});
    })
    .post();

widgetRouter.route("/widgets/:widgetId")
    .get()
    .put()
    .delete();



module.exports = widgetRouter;

but When I try to test the rest api(http://localhost:3000/api/widgets) from postman it says Cannot GET /api/widgets

Upvotes: 3

Views: 1178

Answers (2)

mcek
mcek

Reputation: 490

You can also try that.

rest.js

const express = require('express');
const http = require('http');
const  router = express.Router();

const app = express();

require('./widgets')(app, router);

app.get('/', function(req, res) {
    res.send('Home');
});

app.listen(3000,function(){
    console.log('server started in port 3000');
});

widgets.js

module.exports = function(app, router){
    router.route("/widgets")
        .get(function(req,res){
            res.json({"abc":"hello"});
        })
        .post();

    router.route("/widgets/:widgetId")
        .get()
        .put()
        .delete();

    app.use('/api', router);
});

Upvotes: 1

user5593085
user5593085

Reputation:

You have imported and initialized the express module, but then you start a server with the http module. You should use only Express:

Also you should use app.use('/api',widgetRouter) instead of app.get('/api', widgetRouter) which is an express middleware.

const express = require('express');
const app = express(); 

const widgetRouter = require('./rest/widgets');

app.use('/api', widgetRouter);
app.get('/', function(req, res) {
    res.send('Home');
});

app.listen(3000, function(){
    console.log('server started in port 3000');
});

Upvotes: 6

Related Questions