node.js 错误:大多数中间件(如 bodyParser)不再与 Express 捆绑在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25550819/
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
Error: Most middleware (like bodyParser) is no longer bundled with Express
提问by James Powell
I need to create a web service and I am using Node.js in server. But when I am running in localhost I am getting an error:
我需要创建一个 Web 服务并且我在服务器中使用 Node.js。但是当我在 localhost 中运行时,我收到一个错误:
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
错误:大多数中间件(如 bodyParser)不再与 Express 捆绑在一起,必须单独安装。请参阅https://github.com/senchalabs/connect#middleware。
neo4jtest.js
neo4jtest.js
var config = require('./config');
var bodyParser = require('body-parser');
var app = express();
var neo4jurl = process.env.NEO4J_URL ;
neo4jurl = neo4jurl +'/db/data/';
var query = [ 'START me=node:node_auto_index(name={inputusername}) MATCH me<--friend<--friend_of_friend where (friend_of_friend.entitytype={inputentitytype}) RETURN friend_of_friend;' ];
var insertquery = [ 'CREATE (user {entitytype:{inputentitytype}, name : {inputname}}) return user;' ];
var queryforallrelation = [ 'start n = node:node_auto_index(name={inputusername}) match(n)--(x) return x;'];
// Config
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
// configure stuff here
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
}
app.get('/api', function (req, res) {
res.send('REST API is running');
});
app.get('/friendoffriend/:username', function (req, res){
res.set({'Content-Type': 'text/json'});
username = req.params.username;
type = 'user';
neo4j.connect(neo4jurl, function (err, graph) {
graph.query(query.join('\n'), {inputusername : username, inputentitytype :type} ,function (err, results) {
if (err) {
res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error');
}
else {
res.send(HTTPStatus.OK,JSON.stringify(results));
}
});
});
});
app.get('/insertuser/:username', function (req, res){
res.set({'Content-Type': 'text/json'});
username = req.params.username;
type = 'user';
neo4j.connect(neo4jurl, function (err, graph) {
graph.query(insertquery.join('\n'), {inputname : username, inputentitytype :type} ,function (err, results) {
if (err) {
res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error');
}
else {
res.send(HTTPStatus.OK,JSON.stringify(results));
}
});
});
});
//Cypher Query with Javascript Callback Example
function neo4jQuery(neo4jurl, query, parameters, giveresults) {
neo4j.connect(neo4jurl, function (err, graph) {
graph.query(query.join('\n'), {inputusername : 'andrew'} ,function (err, results) {
if (err) {
giveresults(HTTPStatus.INTERNAL_SERVER_ERROR);
}
else {
giveresults(JSON.stringify(results));
}
});
});
}
app.get('/allrelations/:username', function (req, res){
res.set({'Content-Type': 'text/json'});
username = req.params.username;
parameters = {inputusername : username};
neo4jQuery(neo4jurl, queryforallrelation, parameters, function(results){
res.send(results);
});
});
app.listen(1212);
Following is the error that i got from the console:
以下是我从控制台得到的错误:
C:\node\NodejsNeo4j1-master>node neo4jtest.js
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (C:\node\NodejsNeo4j1-master\node_modules\express\lib\express.js:89:13)
at Object.<anonymous> (C:\node\NodejsNeo4j1-master\neo4jtest.js:26:18)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
采纳答案by mscdex
You need to replace your old bundled middleware usage (express.bodyParser, express.methodOverride, express.errorHandler) with external/separate middleware. The link in the error gives you the names of these new middleware. You may want to check the documentation for these middleware to check for any API changes since Express 3.
您需要使用外部/单独的中间件替换旧的捆绑中间件用法 ( express.bodyParser, express.methodOverride, express.errorHandler)。错误中的链接为您提供了这些新中间件的名称。您可能需要查看这些中间件的文档以检查自 Express 3 以来的任何 API 更改。
回答by James Powell
EDIT: I have posted a fork of Brian's seed with all the changes given below: https://github.com/LossyHorizon/angular-socket-io-seed
编辑:我已经发布了一个布赖恩种子的分支,其中包含以下所有更改:https: //github.com/LossyHorizon/angular-socket-io-seed
I found this discussion while fighting this my self. I am updating my copy of
https://github.com/btford/angular-socket-io-seedbefore I begin a new project. I plan to submit my changes back to Brian Ford when I figure out how.
我在与自己作斗争时发现了这个讨论。在开始新项目之前,我正在更新
https://github.com/btford/angular-socket-io-seed 的副本。当我弄清楚如何做时,我计划将我的更改提交回 Brian Ford。
OLD package.json
旧包.json
"socket.io": "~0.9.16",
"jade": "~0.31.2",
"express": "~3.2.6"
NEW package.json
新的 package.json
"socket.io": "1.1.*",
"jade": "1.6.*",
"express": "4.8.*",
"serve-favicon": "2",
"morgan": "1.3.*",
"method-override":"*", //added missing ,
"body-parser": "1.8",
"errorhandler": "*",
"express-session": "*",
"multer": "0.1.*"
You will need to explicitly add the middle ware that used to be just present, one line:
您将需要显式添加曾经存在的中间件,一行:
var express = require('express');
Becomes a bunch of lines:
变成一堆行:
var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var session = require('express-session');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');
OLD setup code:
旧设置代码:
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
NEW setup code:
新设置代码:
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(session({ resave: true, saveUninitialized: true,
secret: 'uwotm8' }));
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse multipart/form-data
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));
This is the part that took me forever. Sadly once I worked this out I looked in express/lib/application.js, searched for app.listen and there is a wonderful comment that explains things quite nicely. Not sure why I was so slow to look up the source, though it looks like I am not alone in that.
这是让我永远的部分。可悲的是,一旦我解决了这个问题,我查看了 express/lib/application.js,搜索了 app.listen 并且有一个很好的评论,很好地解释了事情。不知道为什么我查找来源如此缓慢,尽管看起来我并不孤单。
Demos, docs, most blog posts, say you start your app with this, and it works, but locks us out from using socket.io (http & https at the same time also).
演示、文档、大多数博客文章都说你用这个启动你的应用程序,它可以工作,但阻止我们使用 socket.io(同时也使用 http 和 https)。
app.listen(app.get('port'), function(){
console.log('Express server on port ' + app.get('port'));
});
This is functionally the same, but makes socket.io usage easy. Look up the source for app.listen() and you will see that this is what it is doing anyway.
这在功能上是相同的,但使 socket.io 的使用变得容易。查找 app.listen() 的源代码,您将看到它无论如何都在执行此操作。
// could be/remain at top of file
var http = require('http');
var server = http.createServer (app);
// delete this line if NOT using socket.io
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log('Express server on port ' + app.get('port'));
});
I does not matter if you use the new express 'standard' syntax, or this syntax, the same http object is used either way, and as I recall http is a built in component to node.js anyway.
如果您使用新的快速“标准”语法或此语法,无论哪种方式都使用相同的 http 对象,我都没有关系,而且我记得 http 无论如何都是 node.js 的内置组件。
I hope this helps someone else.
我希望这对其他人有帮助。
回答by Shinichi-kudo
First you install bodyParser :
npm install body-parserAnd use it:
var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());
首先安装 bodyParser :
npm install body-parser并使用它:
var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());
回答by mscdex
You need install body parser separately via npm:
你需要通过 npm 单独安装 body 解析器:
In your project root:
npm install body-parser
在您的项目根目录中:
npm install body-parser
See
看
https://www.npmjs.org/package/body-parser
https://www.npmjs.org/package/body-parser
https://github.com/strongloop/express/wiki/Migrating-from-3.x-to-4.x
https://github.com/strongloop/express/wiki/Migrating-from-3.x-to-4.x
回答by Chintan Pathak
I am having a similar problem, and havent been able to resolve it yet.
我也遇到了类似的问题,目前还没有解决。
But as per my reading, from various sources you need to:
但根据我的阅读,您需要从各种来源:
Either update your package.json to include the dependencies for all the middleware like:
"dependencies": { "express": "*", "body-parser": "*", "method-override": "*", . . . }or you can just run each one separately on the command prompt as
npm install body-parser --save-dev
You will have to do this for the middleware that you use out of the short list shown hereor the complete list here.
As far as I can make out, in your code, you are using: body-parser, method-override, static and errorhandler.
You will have to remove the line:
app.use(app.router);
as described here
更新您的 package.json 以包含所有中间件的依赖项,例如:
"dependencies": { "express": "*", "body-parser": "*", "method-override": "*", . . . }或者您可以在命令提示符下单独运行每个
npm install body-parser --save-dev
你必须为你使用显示短名单出来中间件做到这一点这里或完整列表在这里。
据我所知,在您的代码中,您使用的是:正文解析器、方法覆盖、静态和错误处理程序。
您将不得不删除该行:
app.use(app.router);
描述在这里
As I said, I am also, working on it. I suggest you make the changes, and tell me if the error on the console changes.
正如我所说,我也在努力。我建议您进行更改,并告诉我控制台上的错误是否更改。

