NodeJS:TypeError:app.use不是函数

时间:2017-07-02 17:20:32

标签: javascript node.js

我正在浏览Connect模块Nodejs的教程。

我写了这段代码:

var http = require('http');
var app = require('connect');
function doFirst(request, response, next) {

    console.log('doFirst');
    next();
}
function doSecond(request, response, next) {

    console.log('doFirst');
    next();
}
app.use(doFirst);
app.use(doSecond);
http.createServer(app).listen(8888);

在运行此应用程序时遇到问题:

C:\Users\sparsh\eclipse-workspace\Delete\ConnectServer.js:13
app.use(doFirst);
    ^

TypeError: app.use is not a function
    at Object.<anonymous> (C:\Users\sparsh\eclipse-workspace\Delete\ConnectServer.js:13:5)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

请帮忙

3 个答案:

答案 0 :(得分:1)

正如评论中提到的jfriend00:使用快递;)

但要回答你的问题。 require( 'connect' )返回一个函数。你需要做的是:

var http = require('http');
var connect = require('connect');

var app = connect();
// ...

另请参阅npm包here

答案 1 :(得分:0)

在宣布app.use之前,您必须:

var app = app();

或更好

var connect = require("connect");

var app = connect();

答案 2 :(得分:0)

只需使用以下代码替换前两行:

var connect = require('connect');
var http = require('http');

var app = connect();

有关详情,请参阅here