Savan Gotrakiya
Savan Gotrakiya

Reputation: 71

unable to find route when specifying routes in separate file

when I type URL localhost:8000 it displays a message in browser "hello world". but when I try localhost:8000/product it doesn't find the right path.

Server.js

const express = require('express');
const http = require('http'); 
const port = 8000;
const app = require('./app');    
http.createServer(function(req,res){
        res.write('Hello World!');
        res.end(); }).listen(port);

app.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const productRoutes = require('./src/helper/routes/product');

console.log('savan');
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));


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

app.get('/', (req,res) => {
    if(req) {
        console.log('request');
    }
    res.end();
});

src/helper/routes/product.js

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

console.log('product');

module.exports = function(productRoutes) {
    productRoutes.get('/', (req, res) => {
        res.write('hii');
        res.render('about');
        console.log('get request...');
    });

    productRoutes.post('/',(req, res) => {
        console.log('post request...');
    });

    return productRoutes;
};

Upvotes: 0

Views: 236

Answers (1)

In the route file, you need to export the route itself instead of wrapping everything in a function.

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

productRoutes.get('/', (req, res) => {
    res.write('hii');
    res.render('about');
    console.log('get request...');
});

productRoutes.post('/',(req, res) => {
    console.log('post request...');
});

module.exports = productRoutes;

or you could keep the function in the route file and call the function to pass the returned express router to the express app in app.js instead of passing the function directly to express.

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

Upvotes: 1

Related Questions