Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否有快捷方式或更短的语法来单独接收req.body的内容?_Javascript_Node.js_Post_Routes - Fatal编程技术网

Javascript 是否有快捷方式或更短的语法来单独接收req.body的内容?

Javascript 是否有快捷方式或更短的语法来单独接收req.body的内容?,javascript,node.js,post,routes,Javascript,Node.js,Post,Routes,我想保存req中的author_id,它不是表单的一部分,而是URL中的一个变量参数 目前,我正在分别从req.body和author\u id以及req.user.id添加表单参数,并通过组合上述两个参数创建一个新对象 router.post("/", middleware.isLoggedIn, function(req, res){ // get data from form and add to campgrounds array var name = req.body.name

我想保存req中的author_id,它不是表单的一部分,而是URL中的一个变量参数

目前,我正在分别从req.body和author\u id以及req.user.id添加表单参数,并通过组合上述两个参数创建一个新对象

router.post("/", middleware.isLoggedIn, function(req, res){
  // get data from form and add to campgrounds array
  var name = req.body.name;
  var image = req.body.image;
  var desc = req.body.description;
  var author = { //not a part of req.body but I want to add it in new object
      id: req.user._id,
      username: req.user.username
  }
  var price = req.body.price;
    var location = req.body.location;
    var newCampground = {name: name, image: image, description: desc, price: price, author:author, location: location};
    Campground.create(newCampground, function(err, newlyCreated){
        if(err){
            console.log(err);
        } else {
            res.redirect("/campgrounds");
        }
    });
  });

我想要一种更短的格式或方法来实现这一点,因为来自req.body的数据将来可能会变得更大&我不想单独提取所有内容并将其与我的作者密钥结合起来。

对于ES6,您可以分解结构,并使用速记属性名称:

const { name, image, description, price, location, user } = req.body;
const author = { id: user._id, username: user._username };
const newCampground = { name, image, description, price, location, author };

// or, without the intermediate `author` variable:

const newCampground = { name, image, description, price, location, author: { id: user._id, username: user._username } };
如果不想重复
req.body
中的所有非
user
属性两次,可以使用类似Lodash的:


使用ES6,您可以分解结构并使用速记属性名称:

const { name, image, description, price, location, user } = req.body;
const author = { id: user._id, username: user._username };
const newCampground = { name, image, description, price, location, author };

// or, without the intermediate `author` variable:

const newCampground = { name, image, description, price, location, author: { id: user._id, username: user._username } };
如果不想重复
req.body
中的所有非
user
属性两次,可以使用类似Lodash的: