node express bodyparser已弃用,新语法不起作用

时间:2016-07-12 12:49:17

标签: node.js express

我正在尝试编写一个简单的html页面,在单击按钮时,将文本输入字段中的值发送到节点服务器,然后在控制台上输入所输入的值。知道使用快递4,不推荐使用上一个bodyparser,并按照此处的讨论进行操作:bodyParser is deprecated express 4

但是使用以下代码时,启动服务器时仍然会出错:

var express = require('express');
var app = express();

app.use(express.static('resources'));
app.use(express.static(__dirname));
app.use(express.bodyParser.urlencoded());

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

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

   console.log("Request for java_preivew:");
   console.log(req.body.url);
})

var server = app.listen(3000, function () {
  console.log("Server started...")
  var host = server.address().address
  var port = server.address().port

  console.log("Listening at http://%s:%s", host, port)
})

HTML:

$(document).ready(function(){
        $('#previewButton').click(function () {
            //var enterURL=$('inputUrl').val();
            //alert("Button Clicked:"+$('#inputUrl').val());
            $.post("java_preview", {url: $('#inputUrl').val()} );
        });

      });

错误日志:

/Users/-/Google Drive/papers/ISWC2016_demo/webpages/node_modules/express/lib/express.js:99
      throw new Error('Most middleware (like ' + name + ') is no longer bundle
            ^
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 (/Users/-/Google Drive/papers/ISWC2016_demo/webpages/node_modules/express/lib/express.js:99:13)
    at Object.<anonymous> (/Users/-/Google Drive/papers/ISWC2016_demo/webpages/startserver.js:6:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

请提出任何建议

3 个答案:

答案 0 :(得分:5)

bodyParser不再是express的一部分。使用npm将其作为依赖项安装,并将其包含在项目中。

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

答案 1 :(得分:0)

从这里删除了express这个词:

app.use(express.static('resources'));
app.use(express.static(__dirname));
app.use(express.bodyParser.urlencoded());

一切都应该有效:)

答案 2 :(得分:0)

您所指的答案相同,说您必须使用 extended:true

If you're still getting a warning with urlencoded you need to use

app.use(bodyParser.urlencoded({
    extended: true
}));
The extended config object key now needs to be explicitly passed, 
since it now has no default value.