Express.js中body-parser的非弃用替代方法

时间:2022-12-19 07:39:37

I am going through the book Web Development with Node and Express and have hit a snag.

我正在浏览“使用Node和Express进行Web开发”一书,并且遇到了障碍。

I was instructed to put the below in my application file, but it looks like body-parser is deprecated and will not work. How can I achieve the same functionality?

我被指示将下面的内容放在我的应用程序文件中,但看起来身体解析器已被弃用并且不起作用。我怎样才能实现相同的功能?

This is my current code:

这是我目前的代码:

app.use(require('body-parser')());

app.get('/newsletter', function(req, res){

    // we will learn about CSRF later...for now, we just
    // provide a dummy value
    res.render('newsletter', { csrf: 'CSRF token goes here' });
});

app.post('/process', function(req, res){

    console.log('Form (from querystring): ' + req.query.form); 
    console.log('CSRF token (from hidden form field): ' + req.body._csrf); 
    console.log('Name (from visible form field): ' + req.body.name); 
    console.log('Email (from visible form field): ' + req.body.email); res.redirect(303, '/thank-you');
});

1 个解决方案

#1


From: bodyParser is deprecated express 4

来自:bodyParser已弃用快递4

It means that using the bodyParser() constructor has been deprecated, as of 2014-06-19.

这意味着自2014-06-19起不再使用bodyParser()构造函数。

app.use(bodyParser()); //Now deprecated

You now need to call the methods separately

您现在需要单独调用这些方法

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

And so on.

等等。

#1


From: bodyParser is deprecated express 4

来自:bodyParser已弃用快递4

It means that using the bodyParser() constructor has been deprecated, as of 2014-06-19.

这意味着自2014-06-19起不再使用bodyParser()构造函数。

app.use(bodyParser()); //Now deprecated

You now need to call the methods separately

您现在需要单独调用这些方法

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

And so on.

等等。