gpt4 book ai didi

Node.js Express : BodyParser Syntax

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:42 28 4
gpt4 key购买 nike

大家好,我是 Node.js 和 Express 的新手。我只是在尝试各种教程中的各种 Node.js 代码。

根据 npm 官方网站,使用 methodOverride 的正确语法是

// Be sure to place after the body parser if you want to accept the method 
// override using a post parameter
app.use(express.bodyParser());

// Accepts a single argument, the name of the method override parameter,
// defaults to "_method"
app.use(require('express-method-override')('method_override_param_name'));

但是当我使用这个时,我收到以下错误

Error: Most middleware (like bodyParser) is no longer bundled with Express and
ust be installed separately. Please see https://github.com/senchalabs/connect#m
ddleware.
at Function.Object.defineProperty.get (E:\node_modules\npm\node_modules\exp
ess\lib\express.js:89:13)

据我研究,app.use(express.bodyParser()) 已被弃用。 Express 不再包含 bodyParser 中间件。所以我的猜测 app.use(bodyParser()) 是正确的,我像这样改变了我的代码

app.use(bodyParser());
app.use(require('express-method-override')('method_override_param_name'));

下面是我的 put 功能代码

app.put('/user/:id', function(req, res){
console.log('Sha Put testing');
console.log(req.body);
//user.findByIdAndUpdate({email: req.params.id},

user.update({email: req.params.id},
{
email: req.body.email,
name: req.body.name,
age : req.body.age
},
function(err, docs){
if(err) res.json('Error here paiyaa -->' + err);
else
{
console.log(docs);
res.redirect('/user/'+req.body.email);
}
});

});

当我用 app.post 替换 app.put 时,它工作正常。但我的任务是实现 PUT 功能。正如 express-method-override 源代码中提到的,我使用了名为 _method 的隐藏字段,这有助于覆盖 POST 方法,并方便 PUT 方法。我的编辑表单代码是

<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
input(type="hidden", name="_method", value="PUT")
p Name:
input(type="text", name="name", value="#{user.name}")
p Age:
input(type="number", name="age", value="#{user.age}")
p
input(type="submit")

当我运行上面的代码时,它在提交表单时抛出以下错误

Cannot POST /user/test@gmail.com

有专家可以帮我解决这个问题并理解一下吗

最佳答案

您有一个使用 app.put 定义的 PUT 路由,但正在尝试 POST 到它。动词需要匹配,因此您的请求应该是 PUT (对您的 user.update 方法有意义),或者将路由更改为 app.post

编辑:查看 express-method-override 的源代码,您的请求正文需要有一个 _method: 'PUT' (默认情况下 - 目前您正在向其传递 'method_override_param_name' 属性,以便中间件覆盖 POST 谓词。

如果还没有,您还应该包含 body-parser 中间件。在命令行上 npm install body-parser 或将其添加到 package.json 并运行 npm install。然后, var bodyParser = require('body-parser'); 将为其余代码提供包含中间件所需的内容。

关于Node.js Express : BodyParser Syntax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515733/

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