router.use()需要中间件函数错误

时间:2017-06-22 00:16:02

标签: javascript node.js

我在学习node.js之后,在线学习本教程之后,我决定练习它。我试图设置服务器但收到错误消息:

 throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
      ^

TypeError: Router.use() requires middleware function but got a undefined
    at Function.use (/Users/user/Desktop/Movie_Review_API/node_modules/express/lib/router/index.js:458:13)

我认为路线有问题,但我不确定是什么。这就是我所拥有的

中间件:

import { Router } from "express";

export default({config, db}) => {
  let api = Router();

  return api;
}

路线:

import express from "express";
import config from "../config"; 
import initializeDb from "../db";
import middleware from "../middleware";
import movie from "../controller/movie";

let router = express();

// connect to db
initializeDb(db => {
router.use(middleware({ config, db }));

  // api routes
  router.use("/movie", movie({config, db}));
});

export default router;

服务器

 import http from "http";
    import express from "express";
    import bodyParser from "body-parser";
    import mongoose from "mongoose";
    import config from "./config";
    import routes from "./routes";

    let app = express();
    app.server = http.createServer(app);

    // middleware
    app.use(bodyParser.json({
      limit : config.bodyLimit
    }));

    // passport config

    // api routes v1
    app.use('/v1', routes);

    app.server.listen(config.port);

    console.log(`Started on port ${app.server.address().port}`);

    export default app;

控制器

import mongoose from "mongoose";
import { Router } from "express";
import movie from "../model/movie";
import bodyParser from "body-parser";

export default({config, db}) => {
  let api = Router();

  api.post("/add", (req, res) => {
    let newMovie = new Movie();
    newMovie.name = req.body.name;
    newMovie.rating = req.body.rating;
    newMovie.releaseYear = req.body.releaseYear;
    newMovie.description = req.body.description;

    newMovie.save(err => {
      if(err) {
        res.send(err);
      }
      res.json({message: "Movie saved successfully"});
    });
  });

1 个答案:

答案 0 :(得分:0)

代表不够,但我建议检查一下:

app.server.listen(config.port);
//can just be 
app.listen(config.port);
通常,只是检查路线,希望工作