简体   繁体   English

Node.js:req.params vs req.body

[英]Node.js: req.params vs req.body

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. 我一直在拼凑几个不同教程的代码,用MEAN堆栈构建一个基本的todo应用程序,使用node,express,angular和mongodb。 One tutorial covered creating an api for GET, POST, and DELETE actions, but neglected the POST. 一个教程包括为GET,POST和DELETE操作创建api,但忽略了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. 当我的功能正常工作时,我遇到了一个涉及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. 可以正常工作来检索待办事项的'_id'属性,并使用它来查找数据库中的相应文档。 Furthermore, when viewing the request in Firefox's developer tools, the todo object appears in JSON format under the "Params" tab. 此外,在Firefox的开发人员工具中查看请求时,todo对象以“Params”选项卡下的JSON格式显示。

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 vs req.body有什么区别,为什么第二个工作而第一个不工作?

req.params is 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 req.params
This property is an object containing properties mapped to the named route “parameters”. 此属性是一个对象,包含映射到命名路由“parameters”的属性。 For example, if you have the route /user/:name, then the “name” property is available as req.params.name. 例如,如果您有route / user /:name,那么“name”属性可用作req.params.name。 This object defaults to {}. 该对象默认为{}。

source: http://expressjs.com/en/4x/api.html#req.params 来源: http//expressjs.com/en/4x/api.html#req.params

req.body 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. 默认情况下,它是未定义的,并且在使用正文解析器和multer等正文解析中间件时会填充。

source: http://expressjs.com/en/4x/api.html#req.body 来源: http//expressjs.com/en/4x/api.html#req.body

req.params is the part you send in the request url parameter or the header part of requests. req.params是您在请求url参数或请求的标题部分中发送的部分。

req.params example in postman 邮差中的req.params示例

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 example in postman 邮递员中的req.body例子

req.body is the JSON data we are sending in postman so we can access it in the post request body part. req.body是我们在邮递员中发送的JSON数据,因此我们可以在邮件请求正文部分中访问它。

route.post('/ninjas',function(req,res,next)
{
    Ninja.create(req.body).then(function(ninja)
    {
        console.log("POST"+req.body);
    res.send(ninja);
    })
    .catch(next);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM