Node.js:req.params 与 req.body
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24976172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: req.params vs req.body
提问by Deimyts
I've been cobbling together code from a few different tutorials to build a basic todo app with the MEAN stack, using node, express, angular, and mongodb. One tutorial covered creating an api for GET, POST, and DELETE actions, but neglected the POST. So, I took it as a challenge to write a function that will update an existing todo. While I got the function working, I encountered an error involving req.params that I didn't understand.
我一直在将几个不同教程中的代码拼凑在一起,以使用 node、express、angular 和 mongodb 使用 MEAN 堆栈构建一个基本的 todo 应用程序。一个教程介绍了为 GET、POST 和 DELETE 操作创建 api,但忽略了 POST。因此,我将编写一个更新现有待办事项的函数视为一项挑战。当我让函数工作时,我遇到了一个我不明白的涉及 req.params 的错误。
Relevant Code:
相关代码:
Node:
节点:
In app.js
在 app.js 中
app.put('/api/todos/:_id', ngRoutes.update);
which leads to:
这导致:
exports.update = function(req, res){
var user_id = req.cookies ?
req.cookies.user_id : undefined;
Todo.findByIdAndUpdate(req.params._id,
{ $set: {
updated_at : Date.now(),
content : req.body.formText
}}, function (err, todo) {
if (err)
res.send(err)
Todo.find({ user_id : user_id}, function(err, todos) {
if (err) res.send(err);
res.json(todos);
});
});
};
Angular:
角度:
$scope.update = function(id) {
$http.put('/api/todos/' + id, this.todo)
.success(function(data) {
console.log(data);
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Jade/HTML:
玉/HTML:
form(ng-submit="update(todo._id)")
input.update-form(ng-show="todo.updating" type="text", name="content", ng-model="todo.formText" placeholder="{{todo.content}}")
This function works fine. It updates the todo in question, and returns the entire list to be reloaded onto the page with the updated value.
此功能工作正常。它更新有问题的待办事项,并返回整个列表以使用更新后的值重新加载到页面上。
However, if in the node code, I change
但是,如果在节点代码中,我更改
content : req.body.formText
to
到
content : req.params.formText
I get the following error as my HTTP response:
我收到以下错误作为我的 HTTP 响应:
Object {
message: "Cast to string failed for value "undefined" at path "content"",
name: "CastError",
type: "string",
path: "content" }
Even while, elsewhere in the function,
即使在函数的其他地方,
req.params._id
works fine to retrieve the todo's '_id' property and use it to find the appropriate document in the database. Furthermore, when viewing the request in Firefox's developer tools, the todo object appears in JSON format under the "Params" tab.
可以很好地检索 todo 的“_id”属性并使用它在数据库中查找适当的文档。此外,在 Firefox 的开发人员工具中查看请求时,todo 对象以 JSON 格式出现在“Params”选项卡下。
Why does this happen? What is the difference between using req.params vs req.body, and why does the second work and the first not?
为什么会发生这种情况?使用 req.params 与 req.body 有什么区别,为什么第二个有效而第一个无效?
回答by 7zark7
req.paramsis for the route parameters, not your form data.
req.params用于路由参数,而不是您的表单数据。
The only param you have in that route is _id:
您在该路线中唯一的参数是_id:
app.put('/api/todos/:_id', ...)
From the docs:
从文档:
req.params
This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.
req.params
这个属性是一个对象,包含映射到命名路由“参数”的属性。例如,如果您有路由 /user/:name,则“name”属性可用作 req.params.name。此对象默认为 {}。
source: http://expressjs.com/en/4x/api.html#req.params
来源:http: //expressjs.com/en/4x/api.html#req.params
req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
req.body
包含请求正文中提交的数据的键值对。默认情况下,它是未定义的,并在您使用 body-parser 和 multer 等正文解析中间件时填充。
回答by Pragyanshu Sharma
req.paramsis the part you send in the request url parameter or the header part of requests.
req.params是您在请求 url 参数中发送的部分或请求的标头部分。
In example above req.params is the data we are sending in postman after ninjas in the
url.
route.delete('/ninjas/:id',function(req,res,next)
{
Ninja.findByIdAndRemove({_id:req.params.id}).then(function(ninja)
{
console.log(ninja.toString());
res.send(ninja);
})
.catch(next);
});
req.body is the part you send in body part of requests
req.body is the JSON data we are sending in postman so we can access it in the post request body part.
req.body 是我们在 postman 中发送的 JSON 数据,因此我们可以在 post 请求正文部分访问它。
route.post('/ninjas',function(req,res,next)
{
Ninja.create(req.body).then(function(ninja)
{
console.log("POST"+req.body);
res.send(ninja);
})
.catch(next);
});

