NodeJS Router.use需要一个中间件函数,但得到了一个Object

j8ag8udp  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(116)

我正在学习express.js并做一个路由器挂载的练习。最新版本的node.jsexpress.js我有一个主要的文件夹。此文件夹包含node-modules文件夹、package和package-lock。这个文件夹也有我创建的3个文件。
main-folder:-
节点模

Package 锁

  1. index.js
  2. router.js
  3. home.js
    Index.js
const express = require('express');
const app = express();

const home = require('./home');
const user = require('./router');

app.use('/', home);
app.use('/router', user);

const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

router.js

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

router.get('/', (req, res) => {
  res.send("Please log to get a user");
});

router.post('/', (req, res) => {
  res.send("Please log to create a user");
});

router.put('/', (req, res) => {
  res.send("Please log to update a user");
});

router.delete('/', (req, res) => {
  res.send("Please log to delete a user");
});

module.exports = router;

home.js

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

app.get('/home', function(req,res){
    res.send("This is my Home page using Express Router");
});

错误:-
TypeError('Router.use()需要一个中间件函数,但得到了一个' + gettype(fn)
TypeError:Router.use()需要一个中间件函数,但得到了一个Object。
我已经浏览了stackoverflow中与上述错误相关的所有主题,并尝试了stackoverflow中提供的每一个解决方案,但没有一个对我有效。
我将感谢您的输入!
谢谢你,谢谢!

dz6r00yl

dz6r00yl1#

你的文件名home.js是一个控制器,它负责渲染你想要在页面上显示的内容。您需要更改home.js index.js和router.js中的代码
index.js

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

const home = require('./home');
const user = require('./router');

app.use('/', user);

const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

router.js

const express = require('express');
const router = express.Router();
const {homePage} = require('./home');

router.get('/', (req, res) => {
  res.send("Please log to get a user");
});
router.get('/home', homePage);

router.post('/', (req, res) => {
  res.send("Please log to create a user");
});

router.put('/', (req, res) => {
  res.send("Please log to update a user");
});

router.delete('/', (req, res) => {
  res.send("Please log to delete a user");
});

module.exports = router;

home.js

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

const homePage = async (req,res) => {
    res.send("This is my Home page using Express Router");
};

module.exports = {homePage}

我希望这对你有用

相关问题