节点更新无效,发送到api时格式错误

时间:2019-02-07 11:41:11

标签: node.js angular api

我尝试将数据从Angular更新到Node.js

component.ts

updatefunction(id,data){
    console.log("component",data);
    //component {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}
    this.uAdminService
      .updateUser(id,data).subscribe(
        result => {
          //console.log(result.json());
        },
        error => {
          console.log(error.json());
        }
      );

  }

在myservice.ts

updatefunction(id, data){
      console.log("service", data);
       //service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}
       let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });
        return this.http.put(this.url+id, data, options);
}

我的nodejs控制器

router.put('/:id', VerifyToken, function (req, res) {
    console.log(req.body);
    //{'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'}
        User.findByIdAndUpdate({_id:req.params.id}, req.body, {new: true}).select("-password")
        .then(users => {
            res.send(users);
        }).catch(err => {
            res.status(500).send({
                message: err.message || "Some error occurred while retrieving Report."
            });
        });


});

我的需求主体控制台是这样的 {'{\ n“ role”:“ User”,\ n“ _id”:“ 5c2dc052d6bfba36b41b34dd” \ n}'},但是我以这种格式从{angle} :“用户”,_id:“ 5c2dc052d6bfba36b41b34dd”,名称:“测试”,电子邮件:“ test123@gmail.com”,//用户名:“测试”}

我不知道为什么要进行转换,以便不更新为db

如果我通过api进行控制台,它将喜欢以下 {名称:“ Test”,电子邮件:“ test123@gmail.com”}

1 个答案:

答案 0 :(得分:0)

如下更新myservice.ts

updatefunction(id, data){
      console.log("service", data);
       //service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}
       let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/json' });
       let options = new RequestOptions({ headers: headers });
       return this.http.put(this.url+id, data, options);
}

在发送Content-Type格式的数据而不是application/json数据时,将json更改为form