我正在尝试编写一个简单的html页面,单击该按钮后,会将文本输入字段中的值发送到节点服务器,然后将其打印在输入值的控制台上。知道在express 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
任何建议请
最佳答案
bodyParser不再是express的一部分。将其安装为npm的依赖项,并将其包含在项目中。
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : false}));
关于node.js - 不赞成使用 Node Express的bodyparser,新语法不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38329399/