【问题标题】:bodyParser is deprecated express 4bodyParser 已弃用 express 4
【发布时间】:2014-08-11 08:57:59
【问题描述】:

我正在使用 express 4.0,并且我知道 body 解析器已从 express 核心中取出,我正在使用推荐的替换,但是我得到了

body-parser deprecated bodyParser: use individual json/urlencoded middlewares server.js:15:12 body-parser deprecated urlencoded: explicitly specify "extended: true" for extended parsing node_modules/body-parser/index.js:74:29

我在哪里可以找到这个假定的中间件?还是我不应该收到此错误?

var express     = require('express');
var server      = express();
var bodyParser  = require('body-parser');
var mongoose    = require('mongoose');
var passport    = require('./config/passport');
var routes      = require('./routes');

mongoose.connect('mongodb://localhost/myapp', function(err) {
    if(err) throw err;
});

server.set('view engine', 'jade');
server.set('views', __dirname + '/views');

server.use(bodyParser()); 
server.use(passport.initialize());

// Application Level Routes
routes(server, passport);

server.use(express.static(__dirname + '/public'));

server.listen(3000);

【问题讨论】:

  • 请注意,对于未来的读者,OP 的脚本使用 var server = express(),但在阅读(似乎全部)以下答案时,假设使用了 var app = express() 行。

标签: node.js express middleware


【解决方案1】:

这意味着使用bodyParser()构造函数已经deprecated,截至2014-06-19。

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

您现在需要分别调用这些方法

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

等等。

如果您仍然收到urlencoded 的警告,您需要使用

app.use(bodyParser.urlencoded({
  extended: true
}));

extended 配置对象键现在需要显式传递,因为它现在没有默认值。

如果您使用的是 Express >= 4.16.0,则在 express.json() 和 express.urlencoded() 方法下重新添加了正文解析器。

【讨论】:

  • @eslammostafa 你可以使用bodyparser,只是不能调用构造函数。您需要调用每个单独的方法。
  • @BenFortune 谢谢 Ben,我明白了,我只是担心 /tmp 的事情,但现在我再次检查,只有当我们使用 bodyParser 解析多部分表单时才会出现 /tmp 问题,andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html然后我将使用强大的多部分表单。
  • extended 是做什么的?
  • 我解释扩展 true 的最佳方式是,不使用扩展意味着curl --data "user[email]=foo&user[password]=bar" localhost:3000/login 将被req.body 中的服务器接收为{ user[email]: "foo", ...},而req.body 将是{user: {email: "foo", ... }} 和@ 987654338@.
  • bodyParser 本身现在被标记为已弃用,可作为 express 的一部分使用,请参阅 Sridhar 的回答 stackoverflow.com/a/59892173/196869、express.json()
【解决方案2】:

想要零警告?像这样使用它:

// Express v4.16.0 and higher
// --------------------------
const express = require('express');

app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));

// For Express version less than 4.16.0
// ------------------------------------
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

说明:extended 选项的默认值已被弃用,这意味着您需要显式传递 true 或 false 值。

Express 4.16.0 及更高版本的注意事项:已重新添加正文解析器以提供开箱即用的请求正文解析支持。

【讨论】:

  • 我使用这个,仍然收到“body-parser deprecated”消息。 app.use(bodyParser.json()).use(bodyParser.urlencoded({ extended: true }));
  • 没错,我在访问构造函数时收到了弃用警告。它作为依赖项包含在 Express 4.17 中):nodejs.dev/learn/get-http-request-body-data-using-nodejs
  • 感谢我的作品,但我有一个问题!那么,现在我们不需要安装 body-parser 了吗?
  • 在 express@4.17.1 上仍然不推荐使用
  • Express 4.16+ body-parser 不再需要安装或使用,因此会出现弃用警告。 express no 直接包含json和urlencoded中间件。
【解决方案3】:

如果你使用的是快递>4.16,你可以使用express.json()和express.urlencoded()

已添加 express.json() 和 express.urlencoded() 中间件以提供开箱即用的请求正文解析支持。这使用了下面的expressjs/body-parser模块模块,因此当前单独需要该模块的应用程序可以切换到内置解析器。

来源 Express 4.16.0 - Release date: 2017-09-28

有了这个,

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

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

成为,

const express = require('express');

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

【讨论】:

  • 意味着我们不再需要安装正文解析器了??
  • 是的。我们不将其作为单独的包裹,因为它现在可以作为 express 的一部分使用。
  • 我得到 SyntaxError: Unexpected token n in JSON at position 6 at JSON.parse ()
【解决方案4】:

不要使用正文解析器

如果您使用的是 Express 4.16+,您可以使用 express 执行此操作:

app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads

您现在可以使用 npm uninstall body-parser 卸载 body-parser



要获取POST内容,可以使用req.body

app.post("/yourpath", (req, res)=>{

    var postData = req.body;

    //Or if this doesn't work

    var postData = JSON.parse(req.body);
});

希望对你有帮助

【讨论】:

    【解决方案5】:

    即使我也面临同样的问题。我提到的以下更改解决了我的问题。

    如果您使用的是 Express 4.16+ 版本,那么

    • 您可能在代码中添加了如下所示的一行:

    app.use(bodyparser.json()); //utilizes the body-parser package
    • 您现在可以将上面的行替换为:

    app.use(express.json()); //Used to parse JSON bodies

    这不应给您的应用程序带来任何重大更改,因为 express.json() 中的代码基于 bodyparser.json()。

    • 如果您的环境中还有以下代码:

    app.use(bodyParser.urlencoded({extended: true}));
    • 您可以将上面的行替换为:

    app.use(express.urlencoded()); //Parse URL-encoded bodies
    • 如果您收到警告说您仍需要将extended 传递给express.urlencoded(),那么请将上述代码更新为:

    app.use(express.urlencoded({ extended: true }));

    最后的注意事项:

    如果您使用 Express 4.16+,您可能不需要将额外的 body-parser 包安装到您的应用程序中。有很多教程包含 body-parser 的安装,因为它们的日期早于 Express 4.16 的发布。

    【讨论】:

    • 这很有趣,因为在express.json() 下使用相同的已弃用body-parse.json()
    • 是的!但不知何故,express.JS 开发团队通过将一行代码替换为另一行代码来简化 json 解析策略/配置,这在语法上并没有太大区别。
    • 我的控制台说我仍然需要使用 express 4.17.1 将extended 传递给express.urlencoded({extended: true})
    • @Hache_raw 我不确定,但我想这取决于您是否以某种方式使用了 UTF-8 编码,或者它现在确实已更改。最好参考一下这个express.js urlencoding link doc。
    【解决方案6】:

    在旧版本的 express 中,我们不得不使用:

    app.use(express.bodyparser()); 
    

    因为 body-parser 是 node 和 表示。现在我们必须像这样使用它:

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    

    【讨论】:

    • 我想你想说“body-parser 是中间件”? express 不是我理解的中间件
    【解决方案7】:

    body-parser 是一个快速中间件 读取表单的输入并将其存储为 javascript 可通过req.body 访问的对象 必须安装“body-parser”(通过npm install --save body-parser)欲了解更多信息,请参阅:https://github.com/expressjs/body-parser

       var bodyParser = require('body-parser');
       app.use(bodyParser.json()); // support json encoded bodies
       app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
    

    当extended 设置为true 时,放气(压缩)的物体将被充气;当 extended 设置为 false 时,将拒绝放气的身体。

    【讨论】:

      【解决方案8】:

      而不是bodyParser.json(),只需使用express.json(), 你不想安装body-parser

      举个例子,

      const express = require("express");
      
      const app = express();
      app.use(express.json());
      

      【讨论】:

        【解决方案9】:

        我在添加时发现

        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({
          extended: true
        }));
        

        帮助,有时是您的查询决定了 express 如何处理它。

        例如,您的参数可能是在 URL 中而不是在正文中传递的

        在这种情况下,您需要同时捕获 body 和 url 参数并使用可用的参数(在以下情况下优先使用 body 参数)

        app.route('/echo')
            .all((req,res)=>{
                let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
                res.send(pars);
            });
        

        【讨论】:

          【解决方案10】:

          你对使用 express-generator 生成骨架项目有什么看法,without deprecated messages 出现在你的日志中

          运行这个命令

          npm install express-generator -g
          

          现在,通过在your Node projects folder 中键入此命令来创建新的 Express.js 启动应用程序。

          express node-express-app
          

          该命令告诉 express 生成名为 node-express-app 的新 Node.js 应用程序。

          然后Go to the newly created project directory、install npm packages和start the app使用命令

          cd node-express-app && npm install && npm start
          

          【讨论】:

          • 这会有帮助吗?
          【解决方案11】:

          body-parser 已弃用 bodyParser:使用单独的 json/urlencoded 中间件 node_modules\express\lib\router\layer.js:95:5

          表示不推荐使用的 req.host:使用 req.hostname 代替 node_modules\body-parser\index.js:100:29

          body-parser deprecated undefined extended:提供扩展选项 node_modules\body-parser\index.js:105:29

          无需更新 express 或 body-parser

          这些错误将被删除。请按照以下步骤操作:-

          1. app.use(bodyParser.urlencoded({extended: true})); // 这将有助于编码。
          2. app.use(bodyParser.json()); // 这将支持 json 格式

          它会运行。

          编码愉快!

          【讨论】:

            【解决方案12】:

            检查这个答案 Stripe webhook error: No signatures found matching the expected signature for payload

            // Use JSON parser for all non-webhook routes
            app.use((req, res, next) => {
              if (req.originalUrl === '/webhook') {
                next();
              } else {
                express.json()(req, res, next);
              }
            });
            
            // Stripe requires the raw body to construct the event
            app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
              const sig = req.headers['stripe-signature'];
            
              let event;
            
              try {
                event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
              } catch (err) {
                // On error, log and return the error message
                console.log(`❌ Error message: ${err.message}`);
                return res.status(400).send(`Webhook Error: ${err.message}`);
              }
            
              // Successfully constructed event
              console.log('✅ Success:', event.id);
            
              // Return a response to acknowledge receipt of the event
              res.json({received: true});
            });
            

            【讨论】:

              猜你喜欢
              • 2021-06-06
              • 2019-05-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-03-04
              • 1970-01-01
              • 1970-01-01
              • 2013-03-28
              相关资源
              最近更新 更多