大家好我是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'));
以下是我的功能代码
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
有些专家可以帮我解决这个问题,并明白了吗
答案 0 :(得分:0)
您使用PUT
定义了app.put
路由,但正在尝试POST
。{}动词需要匹配,因此您的请求应该是PUT
(对user.update
方法有意义)或将路线更改为app.post
。
修改的:
查看express-method-override
的来源,您的请求正文需要_method: 'PUT'
(默认情况下 - 当前您正在传递'method_override_param_name'
属性,以便中间件覆盖{ {1}}动词。
如果您还没有,那么您还应该包含正文解析器中间件。在命令行上POST
或将其添加到npm install body-parser
并运行package.json
。然后,npm install
将为代码的其余部分提供包含中间件所需的内容。