我可以替换app.use(express.bodyParser());

时间:2017-03-06 01:28:38

标签: javascript node.js express

我收到此错误...

  

connect deprecated multipart:use parser(multiparty,busboy,   强大的)npm模块   node_modules / connect / lib / middleware / bodyParser.js:56:20 connect   deprecated limit:限制读取位置的请求大小   node_modules /连接/ LIB /中间件/ multipart.js:86:15

当我在这里学习本教程时:

https://code.tutsplus.com/tutorials/introduction-to-express--net-33367

并且评论说不要使用它。当然,当我删除此声明时,错误消失了

错误的代码再次出现在这里:

app.use(express.bodyParser());

完整的代码在这里:

var express = require('express');
var hbs = require('hbs');
var path = require('path');
var blogEngine = require('./blog');

var app = express();

var path_index = '../web_arcmarks/packet.html';
var path_index_resolved = path.resolve(path_index);


app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.bodyParser());
app.use(express.static('public'));


// add templates

app.get('/', function(req, res) {
    res.render('index',{title:"My Blog", entries:blogEngine.getBlogEntries()});
});

app.get('/about', function(req, res) {
    res.render('about', {title:"About Me"});
});

app.get('/article/:id', function(req, res) {
    var entry = blogEngine.getBlogEntry(req.params.id);
    res.render('article',{title:entry.title, blog:entry});
});

app.listen(3000);

blog.js看起来像这样:

var entries = [
{"id":1, "title":"Hello World!", "body":"This is the body of my blog entry. Sooo exciting.", "published":"6/2/2013"},
{"id":2, "title":"Eggs for Breakfast", "body":"Today I had eggs for breakfast. Sooo exciting.", "published":"6/3/2013"},
{"id":3, "title":"Beer is Good", "body":"News Flash! Beer is awesome!", "published":"6/4/2013"},
{"id":4, "title":"Mean People Suck", "body":"People who are mean aren't nice or fun to hang around.", "published":"6/5/2013"},
{"id":5, "title":"I'm Leaving Technology X and You Care", "body":"Let me write some link bait about why I'm not using a particular technology anymore.", "published":"6/10/2013"},
{"id":6, "title":"Help My Kickstarter", "body":"I want a new XBox One. Please fund my Kickstarter.", "published":"6/12/2013"}];


exports.getBlogEntries = function() {
    return entries;
};

exports.getBlogEntry = function(id) {
    for(var i=0; i < entries.length; i++) {
        if(entries[i].id == id) return entries[i];
    }
};

1 个答案:

答案 0 :(得分:2)

您正在查看一个不针对Express 4.0的旧教程。在Express 4.0中,bodysarser与Express分离,并且位于一个单独的模块中。以前的内置版现已弃用。

您显示的代码似乎根本不需要body-parser模块。但是,如果你确实有一些需要它的代码,那么你应该使用单独的body-parser模块:

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));

注意:正文解析器模块中有多个不同的中间件,因此您需要安装所需的正确的中间件(这只是上面的一个示例)。正文解析器模块的文档是here