【问题标题】:Node update not working, format is wrong while send to api节点更新不起作用,发送到 api 时格式错误
【发布时间】:2019-02-07 23:39:04
【问题描述】:

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

组件.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."
            });
        });


});

我的 req.body 控制台像这样 {'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'} 但我以这种格式从 angularjs 传递 {role : "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}

我不知道为什么它会转换,所以它不会更新到 db

如果我从 api 控制台它会喜欢这样 { name: "Test",email: "test123@gmail.com"}

【问题讨论】:

    标签: node.js angular api


    【解决方案1】:

    更新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 数据。

    【讨论】:

    • 如果我使用 application/json,我已经尝试过了。 req.body 返回空
    • 你在使用body-parser中间件并解析json数据吗?
    • 我用这个app.use(bodyParser.urlencoded({extended: false }));
    • 如果我打印 res.send(users);更新后它只会显示以前的重新编码而不是新的
    • 另加app.use(bodyParser.json());
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多