Javascript 类型错误:app.use() 需要中间件函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32883626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:19:02  来源:igfitidea点击:

TypeError: app.use() requires middleware functions

javascriptnode.js

提问by Nkav

This is my server.js file and api.js file. I am getting an error in the sort function in which I intend to search the js objects according to their attributes.The event Schema has the attributes as name, location, price, rating. I tried to sort it according to their prices.

这是我的 server.js 文件和 api.js 文件。我在排序函数中遇到错误,我打算在其中根据属性搜索 js 对象。事件架构具有名称、位置、价格、评级等属性。我试图根据他们的价格对它进行排序。

server.js

服务器.js

var express= require('express');
var bodyParser= require('body-parser');
var morgan = require('morgan');
var config=require('./config');
var app= express();
var mongoose=require('mongoose');
//var User=require('./database/user')
mongoose.connect('mongodb://localhost:27017/db',function(err){
    if(err){
        console.log(err);
    }
    else{
        console.log("connected!");
    }
});

app.use(bodyParser.urlencoded({extended: true })); //if false then parse only strings
app.use(bodyParser.json());
app.use(morgan('dev'));//log all the requests to the console
var api=require('./app/routes/api')(app,express);
app.use('/api',api);
app.get('*',function(req,res){
    res.sendFile(__dirname + '/public/views/index.html');
});   // * means any route

app.listen(config.port,function(err){
    if(err){enter code here
        console.log(err);
    }
    else{
        console.log("The server is running");
    }
});
module.exports = router;

api.js

api.js

var User = require('../models/user');
var Event = require('../models/event');
var config = require('../../config');
var secret = config.secretKey;

module.exports = function (app, express) {
    var api = express.Router();
    app.use()

    api.post('/signup', function (req, res) {
        var user = new User({
            name: req.body.name,
            username: req.body.username,
            password: req.body.password
        });
        user.save(function (err) {
            if (err) {
                res.send(err);
                return;
            }
            res.json({
                message: 'User created!'
            });
        });

    });

    api.get('/users', function (req, res) {
        User.find({}, function (err, users) {
            if (err) {
                res.send(err);
                return;
            }
            res.json(users);
        });
    });

    api.post('/eventfeed', function (req, res) {
        var event = new Event({
            name: req.body.name,
            location: req.body.location,
            description: req.body.description,
            price: req.body.price,
            rating: req.body.rating
        });

        event.save(function (err) {
            if (err) {
                res.send(err);
                return;
            }
            res.json({
                message: 'Event created!'
            });
        });
    });

    // utility function for sorting an array by a key in alpha order
    api.get('/sortby_price', function (err) {
        if (err) return err;
            // utility function for sorting an array by a key in parsed numeric order
        else {
            function sortArrayNum(arr, key) {
                arr.sort(function (a, b) {
                    return parseInt(a[key], 10) - parseInt(b[key], 10);
                });
            }

            var dicts = EventSchema.saved;
            for (var i = 0; i < dicts.length; i++) {
                var terms = dicts[i].terms;
                sortArrayNum(terms, "price");
            }
        }
        return api;
    });
}

This is my error. I am making a webpage for the first time using this. Kindly help me what does this error tells.

这是我的错误。我是第一次使用这个制作网页。请帮助我这个错误说明了什么。

TypeError: app.use() requires middleware functions
at EventEmitter.use (c:\Users\MY APY\WebstormProjects\Main\node_modules\express\lib\application.js:209:11)
at module.exports (c:\Users\MY LAPY\WebstormProjects\Main\app\routes\api.js:10:9)
at Object. (c:\Users\MY LAPY\WebstormProjects\Main\server.js:20:36)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3

TypeError: app.use() 需要
EventEmitter.use (c:\Users\MY APY\WebstormProjects\Main\node_modules\express\lib\application.js:209:11)
at module.exports (c:\Users ) 的中间件函数\MY LAPY\WebstormProjects\Main\app\routes\api.js:10:9)
在对象。(c:\Users\MY LAPY\WebstormProjects\Main\server.js:20:36)
在 Module._compile (module.js:460:26)
在 Object.Module._extensions..js (module.js:478: 10)
在 Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
在启动时(节点。 js:129:16)
在 node.js:814:3

回答by sunyata

I had this problem when I left out

我离开时遇到了这个问题

module.exports = routers

in my Routes.js

在我的 Routes.js 中

In my server.js, I had

在我的 server.js 中,我有

var mainRoutes = require('./Routes.js')
app.use(mainRoutes)

So check your 'app/routes/api' file to see if it has proper export.

所以检查你的“app/routes/api”文件,看看它是否有正确的导出。

回答by Riyaz Parve

Middleware is a function with access to the request object (req), the response object (res), and the next middleware in the application's request-response cycle, commonly denoted by a variable named next.

中间件是一个函数,可以访问请求对象 (req)、响应对象 (res) 和应用程序请求-响应循环中的下一个中间件,通常由名为 next 的变量表示。

Middleware can:

中间件可以:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.
  • 执行任何代码。
  • 对请求和响应对象进行更改。
  • 结束请求-响应循环。
  • 调用堆栈中的下一个中间件。

If the current middleware does not end the request-response cycle, it must call next() to pass control to the next middleware, otherwise the request will be left hanging.

如果当前中间件没有结束请求-响应循环,则必须调用 next() 将控制权传递给下一个中间件,否则请求将被挂起。

In api.js line number 10 is invalid

在 api.js 中,第 10 行无效

app.use()

app.use must have a function with 3 params

app.use 必须有一个带有 3 个参数的函数

// a middleware with no mount path; gets executed for every request to the app
app.use(function (req, res, next) {
   console.log('Time:', Date.now());
   next();
});

if you want only few selected paths to use this middleware you can do something like this

如果你只想要几个选定的路径来使用这个中间件,你可以做这样的事情

// a middleware mounted on /user/:id; will be executed for any type of HTTP request to /user/:id
app.use('/user/:id', function (req, res, next) {
   console.log('Request Type:', req.method);
   next();
});

// a route and its handler function (middleware system) which handles GET requests to /user/:id
app.get('/user/:id', function (req, res, next) {
   res.send('USER');
});

Take a look at the expressjs documents it is pretty good. http://expressjs.com/guide/using-middleware.html

看一下expressjs文档,还不错。 http://expressjs.com/guide/using-middleware.html

回答by Dan Pantry

app.userequires that you pass it a function which is then used as middleware. You have two instances where you do not do this which will cause this error; both of which are in api.js.

app.use要求您向它传递一个函数,然后将其用作中间件。您有两个不这样做会导致此错误的实例;两者都在api.js.

api.js:10app.use()

api.js:10app.use()

You do not pass a function to .use(), and so this will cause an error. This is the error you're seeing in your post.

您没有将函数传递给.use(),因此这将导致错误。这是您在帖子中看到的错误。

However, you will get another error:

但是,您将收到另一个错误:

var api=require('./app/routes/api')(app,express);
app.use('/api',api);

This section attempts to mount the return value of your ./app/routes/apimodule function as a middleware. However, we can see inside your code that you do not actually return a value from the function in api.js; you instead return the router from inside a route handler..

本节尝试将./app/routes/api模块函数的返回值挂载为中间件。但是,我们可以在您的代码中看到您实际上并未从 api.js 中的函数返回值;你改为从路由处理程序内部返回路由器..

// utility function for sorting an array by a key in alpha order
api.get('/sortby_price', function (err) {
    if (err) return err;
        // utility function for sorting an array by a key in parsed numeric order
    else {
        function sortArrayNum(arr, key) {
            arr.sort(function (a, b) {
                return parseInt(a[key], 10) - parseInt(b[key], 10);
            });
        }

        var dicts = EventSchema.saved;
        for (var i = 0; i < dicts.length; i++) {
            var terms = dicts[i].terms;
            sortArrayNum(terms, "price");
        }
    }
    return api; // <- this will be returned inside the app.get call
});

You should instead move this out of the handler and to the end of your function.

您应该将其移出处理程序并移至函数的末尾。

The total amended code will look like this:

修改后的总代码如下所示:

module.exports = function (app, express) {
    var api = express.Router();
    ..omitted for brevity..

    // utility function for sorting an array by a key in alpha order
    api.get('/sortby_price', function (err) {
        if (err) return err;
            // utility function for sorting an array by a key in parsed numeric order
        else {
            function sortArrayNum(arr, key) {
                arr.sort(function (a, b) {
                    return parseInt(a[key], 10) - parseInt(b[key], 10);
                });
            }

            var dicts = EventSchema.saved;
            for (var i = 0; i < dicts.length; i++) {
                var terms = dicts[i].terms;
                sortArrayNum(terms, "price");
            }
        }
    });
    return api;
}