每当我尝试使用app.use()
初始化路由时,从路由目录调用路由器时都会出错。我得到的错误是说Router.use()
需要一个middleware
函数,但得到了一个Object
。
我不确定下面的代码到底有什么问题
错误:
C:\ Users \ Desktop \ Projet \ test \ Todo \ node_modules \ express \ lib \ router \ index.js:458 抛出新的TypeError('Router.use()需要中间件功能,但是得到了'+ gettype(fn)) ^
TypeError:Router.use()需要一个中间件功能,但有一个Object 在Function.use(C:\ Users \ Desktop \ Projet \ test \ Todo \ node_modules \ express \ lib \ router \ index.js:458:13) 在对象。 (C:\ Users \ Desktop \ Projet \ test \ Todo \ server \ api \ index.js:3:8) 在Module._compile(module.js:652:30) 在Object.Module._extensions..js(module.js:663:10) 在Module.load(module.js:565:32) 在tryModuleLoad(module.js:505:12) 在Function.Module._load(module.js:497:3) 在Module.require(module.js:596:17) 在要求时(internal / module.js:11:18) 在对象。 (C:\ Users \ Desktop \ Projet \ test \ Todo \ server.js:23:13) 在Module._compile(module.js:652:30) 在Object.Module._extensions..js(module.js:663:10) 在Module.load(module.js:565:32) 在tryModuleLoad(module.js:505:12) 在Function.Module._load(module.js:497:3) 在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}'));
和我的控制器路由所在的文件:
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);
});
});
答案 0 :(得分:0)
//Init express
const app = express();
//Get and Set API routes
const api = require('./server/api/');
app.use('/api',apiRoutes)
将apiRoutes更改为api。 apiRoutes未定义
在设置路由器之前初始化快递。