gpt4 book ai didi

javascript - Nodejs Router 需要函数但得到一个对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:09 25 4
gpt4 key购买 nike

每当我尝试使用 app.use() 初始化路由时,从路由目录调用路由器时都会收到错误。我收到的错误说 Router.use() 需要一个 middleware 函数,但得到一个 Object。我不确定下面的代码到底有什么问题

错误:

C:\Users\Desktop\Projet\test\Todo\node_modules\express\lib\router\index.js:458 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^

TypeError: Router.use() requires a middleware function but got a Object at Function.use (C:\Users\Desktop\Projet\test\Todo\node_modules\express\lib\router\index.js:458:13) at Object. (C:\Users\Desktop\Projet\test\Todo\server\api\index.js:3:8) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at Object. (C:\Users\Desktop\Projet\test\Todo\server.js:23:13) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3) at Function.Module.runMain (module.js:693:10)

我的server.js:

//Import dependencies

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');



//Connect to MongoDB server

mongoose.connect('mongodb ://localhost/todoApp');
mongoose.set('debug',true);

//Import models

require('./server/models/Task');
require('./server/models/Todo');

//Get and Set API routes

const api = require('./server/api/');
app.use('/api',apiRoutes)

//Init express

const app = express();

//Enable bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

//Enable CORS

app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","GET, POST ,DELETE, PUT");
res.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization")
next()
});

//Get env port

const port = process.env.PORT || "3000";
app.set('port',port);

//Create HTTP server.

const server = http.createServer(app);

//Listen on port

server.listen(port,() => console.log('Api running on localhost :${port}'));

并记录我的 Controller 的路线:

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

router.use('/todo',require('./todo'));
router.use('/todo/task',require('./task'));



module.exports = router ;

待办事项文件:

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

const Todo = mongoose.model('Todo');
const Task = mongoose.model('Task');

router.param('todo', function (req, res, next, id) {
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return res.sendStatus(422);
}

Todo.findById(id)
.populate('tasks')
.then(function (todo) {
if (!todo) { return res.sendStatus(404); }

req.todo = todo;

return next();
});
});

router.get('/',(req,res)=>{
Todo.find()
.populate('tasks')
.then((todos)=>{
if (!todos){return res.sendStatus(404);}

return res.json({
todos:todos.map((todo)=>{
return todo.toDto();
})
}).statusCode(200);
});
});

router.post('/', (req, res) => {
if (!req.body.title) {
res.sendStatus(422);
}

let todo = new Todo();
todo.title = req.body.title;

todo.save().then(() => {
res.json(todo.toDto()).statusCode(201);
})

});

router.delete('/:todo', (req, res) => {

req.todo.remove().then(function () {
return res.sendStatus(200);
});
});

任务文件:

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

const Todo = mongoose.model('Todo');
const Task = mongoose.model('Task');


router.param('task',function(req,res,next,id){
if(!id.match(/^[0-9a-fA-F]{24}$/)){
return res.sendStatus(422);
}
Task.findById(id).then ((task) =>{
if(!task){return res.sendStatus(404);}
req.task = task;

return next();
})
})

router.post('/', (req, res) => {
if (!req.body.todoId || !req.body.content) {
res.sendStatus(422);
}

if (!req.body.todoId.match(/^[0-9a-fA-F]{24}$/)) {
res.sendStatus(422);
}

Todo.findById(req.body.todoId).then((todo) => {
if (!todo) { res.statusCode(404); }

let task = new Task();
task.content = req.body.content;
task.state = false;
task.todo = todo;

task.save().then(() => {

todo.tasks.push(task);

todo.save().then(() => {
res.json(task.toDto()).statusCode(201);
});
});
});
});

router.put('/', (req, res) => {

if (req.body.state == undefined || !req.body.id) {
res.sendStatus(422);
}

if (!req.body.id.match(/^[0-9a-fA-F]{24}$/)) {
res.sendStatus(422);
}


Task.findById(req.body.id).then((task) => {
task.state = req.body.state;

task.save().then(() => {
res.json(task.toDto()).statusCode(200);
});
});
});

router.delete('/:task', (req, res) => {
let task = req.task;

task.remove().then(() => {
res.sendStatus(200);
});
});

最佳答案

//Init express
const app = express();

//Get and Set API routes

const api = require('./server/api/');
app.use('/api',apiRoutes)

将 apiRoutes 更改为 api。 apiRoutes 未定义
设置路由器之前先初始化express。

关于javascript - Nodejs Router 需要函数但得到一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51009393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com