nodejs 使用app.use(express.bodyParser()); 出错
程序员文章站
2024-02-01 16:35:10
...
Error: Most middleware (like bodyParser) is no longer bundled with Express and m ust be installed separately. Please see https://github.com/senchalabs/connect#mi ddleware. at Function.Object.defineProperty.get (C:\Users\Administrator\AppData\Roamin g\npm\node_modules\express\lib\express.js:89:13) at Object.<anonymous> (C:\Users\Administrator\Desktop\nodejs\http\express1.j s:4:17) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:902:3
根据错误可以知道bodyparser已经不和Express绑定在一起了,而需要单独来安装,执行如下命令即可:
npm install body-parser
然后在代码中如下使用:
var bodyParser = require('body-parser'); app.use(bodyParser());
不过还是无法工作,提示如下:
body-parser deprecated bodyParser: use individual json/urlencoded middlewares ex press1.js:4:9 body-parser deprecated undefined extended: provide extended option node_modules\ body-parser\index.js:75:29 express deprecated res.send(status): Use res.status(status).end() instead expres s1.js:6:6
然后,可以发现已经过期了,可以使用如下代码代替:
// parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json())
我最终的一个实现如下:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.all('/', function(req, res) { res.send(req.body.title + req.body.text); }); app.listen(3000);
私人广告模块。。。下面依然是我建的一个公众帐号,可以关注一下哦,谢谢