ghost.rider10
ghost.rider10

Reputation: 13

NodeJS routes not getting called using Express

I am trying to build a basic rest api using nodeJS. But when I'm trying to call any endpoint none of them are getting called. What changes should i make in order to make it work. Please help.

const express = require('express') ;
const app = express() ;
const morgan = require('morgan') ;
const bodyParser = require('body-parser') ;

const productRoutes = require('./api/routes/products') ;
const orderRoutes = require('./api/routes/orders') ;

console.log('abc1') ;

//middleware
app.use(morgan('dev')) ;
app.use(express.urlencoded({ extended: true }));
app.use(express.json);

console.log('abc2') ;

//routes
app.use('/products' , productRoutes ) ;
//console.log('abc5') ;
app.use('/orders' , orderRoutes) ;


//delete it later
app.get('/' , (req , res, next) => {
    res.status(200).json({
        message: 'done'
    }) ;
}) ;
//delete end

//for 404 / not found error
app.use((req,res,next) => {
    const error = new Error('not found');
    error.status = 404 ;
    next(error);
});

//handle any error
app.use((error , req, res,next) => {
    res.status(error.status || 500) ;
    res.json({
        message : error.message 
    }) ;
});

module.exports = app ;

my app.js file

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

router.get('/' , (req,res,next) =>{
    console.log('abc') ;
    res.status(200).json({
        message : 'In get routes'
    }
    ) ;
}) ;

router.post('/' , (req,res,next) =>{
    res.status(201).json({
        message : 'In post routes'
    }
    ) ;
}) ;

router.get('/:productId' , (req,res,next) =>{
    res.status(200).json({
        message : 'In get routes' + req.params.productId 
    }
    ) ;
}) ;

module.exports = router ;

my products.js file

const http = require('http') ;
const app = require('./app') ;

const port = process.env.PORT || 3000 ;
console.log(port) ;

const server = http.createServer(app);

server.listen(port) ;

my server.js file

When I'm trying to run the server it runs normally. And the console.logs are also working fine. And also no error is getting thrown.

Upvotes: 1

Views: 923

Answers (1)

Yasmin M
Yasmin M

Reputation: 26

First, change your:

app.use(bodyParser.json);

to:

app.use(bodyParser.json())

Second, you are not listening to any port. You need to add this to your app.js:

const port = 4000
app.listen(port, () => console.log(`App is at port: ${port}!`))

and yes, add a slash to the route(s):

app.use('/products', productRoutes);

Upvotes: 1

Related Questions