外部路由在 express js 中不起作用

external routing is not working in express js

这是我的 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");
});

这是我的外部路由文件

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;

如何将外部路由连接到 main.js 文件。这里我使用的是模块方法。

如果我尝试使用 require 方法,它会正常工作。我不确定,但我认为问题出在这里

app.use(("./user-route/admin-route.js"));

我想你要找的是类似这个的东西?您真正缺少的是 app.use 路由部分,它有两个参数。

app.use('/admin', AdminRouter);

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");
});

外部路由文件

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;

是的,就是这个问题:

app.use(("./user-route/admin-route.js"));

您不能将文件名传递给 app.use() 并期望它起作用(事实上,它会引发错误)。

但你很接近:

app.use(router);