Home > other >  Node.JS Express routing not working as it should work
Node.JS Express routing not working as it should work

Time:07-26

File structure:

file structure

In /server/routes/index.js

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

const deviceRouter = require('./deviceRouter');
const brandRouter = require('./brandRouter');
const typeRouter = require('./typeRouter');
const userRouter = require('./userRouter');

router.use('/user', userRouter);
router.use('/type', typeRouter);
router.use('/brand', brandRouter);
router.use = router.use('/device', deviceRouter);

module.exports = router;

In server/index.js

const router = require('routes/index')

I got an error at this part. Basically, error comes from /server/routes/index.js as

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

Here is how it looks in WebStorm:

here is how it looks in WebStorm

and here is how it should look in WebStorm:

and here is how it should look in WebStorm

CodePudding user response:

Don’t do that :

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

Try this instead :

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

Test with this exemple and if it works then try to adapt it in your project :

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

router.get("/index", (req, res)=> {
 res.json({
   message: "success"
 })
});

In your index file try this :

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

app.use("/user", userRouter);

CodePudding user response:

Change the code in /server/routes/index.js to the following and paste it into server/index.js:

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

const deviceRouter = require('./routes/deviceRouter');
const brandRouter = require('./routes/brandRouter');
const typeRouter = require('./routes/typeRouter');
const userRouter = require('./routes/userRouter');

app.use('/user', userRouter);
app.use('/type', typeRouter);
app.use('/brand', brandRouter);
app.use('/device', deviceRouter);

Delete this file: /server/routes/index.js. No need to make this file server/router/index.js for routes, instead call all your routes the way I did. And if you still want to keep all routes in server/routes/index.js file then do in the following way:

Add in server/index.js:

const indexRoutes = require('./routes/index');

app.use(indexRoutes);

Change server/routes/index.js file to:

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

const deviceRouter = require('./deviceRouter');
const brandRouter = require('./brandRouter');
const typeRouter = require('./typeRouter');
const userRouter = require('./userRouter');

app.use('/user', userRouter);
app.use('/type', typeRouter);
app.use('/brand', brandRouter);
app.use('/device', deviceRouter);

module.exports = app;

And that's all, you are good to go.

  • Related