【问题标题】:Angular 5 send data from angular to expressAngular 5从角度发送数据以表达
【发布时间】:2018-09-29 11:59:25
【问题描述】:

我会使用 subscribe 将我的数据从 angular 发送到 express,但它不起作用。

这是我来自 Angular 的 ProfileComponent.ts :

  updateProfileCompany(e){
    var getUser = localStorage.getItem('user');
    getUser = JSON.parse(getUser)
    var id_student = getUser["id"];
    var nim        = getUser["nim"];
    var nama       = getUser["nama"];
    var email      = getUser["email"];
    var id_company = this.company;
    const user = {
      id         : id_student,
      nama       : nama,
      email      : email,
      nim        : nim
    }
    console.log(user);
    this.authService.updateProfileCompany(user)
    .subscribe((res:Response) => this.user = user);
  }

这是我的 authService.ts :

    updateProfileCompany(user){
    let headers = new Headers();
    this.loadToken();
    var users = localStorage.getItem(this.user);
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json')
    return this.http.put('http://192.168.100.10:3000/users/update', user, {headers: headers})
    .map(res => res.json());
  }

并且在我的快递上给用户未定义的价值。

router.put('/update', passport.authenticate('jwt', {session:false}), (req, res, next)=>{
    user = req.user;
    var id_student = user.id;
    var id_company = req.body.company; 
    var result = [];
    console.log(user.id_student);
});

当我尝试从 angular 控制台记录所有用户数据时,它返回未定义。

【问题讨论】:

  • 你在哪里得到undefined 那个路由被调用了吗?

标签: angular express mean


【解决方案1】:

您在 ajax 请求中发送的用户对象位于 req.body 对象中

router.put('/update', passport.authenticate('jwt', {session:false}),(req, res, next)=>{
    user = req.body; // here
    var id_student = user.id;
    // var id_company = req.body.company; this you should add to the object that you are sending
    var result = [];
    console.log(user.id);
});

发送的用户对象有这个结构

const user = {
  id         : id_student,
  nama       : nama,
  email      : email,
  nim        : nim
}

所以你不能做 console.log(user.id_student) 因为不在那里。

改为执行 console.log(user.id)

【讨论】:

  • const user = { id : id_student, nama : nama, email : email, nim : nim, id_company : "ID Company" } 但是如果我 console.log id_company 它返回 undefined
  • console.log(user.id_company)
  • 返回未定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 2018-11-06
  • 1970-01-01
  • 2018-12-09
  • 2013-03-12
  • 2019-09-07
  • 1970-01-01
相关资源
最近更新 更多