[英]external routing is not working in express js
here is my main.js file这是我的 main.js 文件
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.如何将外部路由与 main.js 文件连接起来。 here I am using the module method.这里我使用的是模块方法。
if i try with require method than it's work properly.如果我尝试使用 require 方法,它就可以正常工作。 i am not sure but i think problem is here我不确定,但我认为问题就在这里
app.use(("./user-route/admin-route.js"));
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 路由部分,有两个参数。
app.use('/admin', AdminRouter);
Main.js file Main.js 文件
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;
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).您不能将文件名传递给app.use()
并期望它能够工作(实际上,它会引发错误)。
But you were close:但你很接近:
app.use(router);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.