here is my main.js file
import express from 'express';
// route file are import here
import router from "./user-route/admin-route.js";
// **************** global variable are define here
const app = express();
const port = 5000;
app.use(express.json());
app.use(("./user-route/admin-route.js"));
/// ***************** routing are created are here
app.get("/", (req, res) => {
res.send("Hello from the server");
});
// ****************** server is created here
app.listen(port, () => {
console.log("Server is Ready and Running on Port 5000");
});
and here is my external routing file
import express from 'express';
const router = express.Router();
const admin = (req, res, next) => {
res.send("Hlo from the dashboard");
}
/// admin routers are defined here
router.route("/admin").get(admin);
export default router;
how I can connect the external routing with main.js file. here I am using the module method.
if i try with require method than it's work properly. i am not sure but i think problem is here
app.use(("./user-route/admin-route.js"));
CodePudding user response:
Yes, this is the issue:
app.use(("./user-route/admin-route.js"));
You can't pass a filename to app.use()
and expect it to work (in fact, it throws an error).
But you were close:
app.use(router);
CodePudding user response:
I think what your looking for is something similar to this? What you're missing really is the app.use routing part, there are two parameters for that.
app.use('/admin', AdminRouter);
Main.js file
import express from 'express';
// route file are import here
const AdminRouter = require('./user-route/admin-route.js')
// **************** global variable are define here
const app = express();
const port = 5000;
app.use(express.json());
/// ***************** routing are created are here
app.get("/", (req, res) => {
res.send("Hello from the server");
});
app.use('/admin', AdminRouter);
// ****************** server is created here
app.listen(port, () => {
console.log("Server is Ready and Running on Port 5000");
});
external routing file
const express = require('express');
const router = express.Router();
/// admin routers are defined here
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;