gpt4 book ai didi

node.js - Node 表达 bodyparser 已弃用,新语法不起作用

转载 作者:行者123 更新时间:2023-12-02 10:12:37 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的 html 页面,单击按钮后,将文本输入字段中的值发送到 Node 服务器,然后在控制台上打印输入的值。要知道,在 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 表达 bodyparser 已弃用,新语法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38329399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com