angular2 http post请求获取res.json()

时间:2017-05-09 10:05:35

标签: javascript json node.js angular angular2-services

我目前正在制作简单的用户身份验证应用。

现在我已经完成了使用节点js和passport的后端进程。

我所做的就是在身份验证进展顺利的情况下返回json响应。

router.post('/register', (req, res) => {

if(!utils.emailChecker(req.body.username)) {
    return res.status(403).json({
        error: "Invalid Username",
        code: 403
    });
}

if(!utils.passwordChecker(req.body.password)) {
    return res.status(403).json({
        error: "Invalid Password",
        code: 403
    });
}

//mysql query : variables must be inside "" or '';
let sql = `SELECT * FROM users WHERE username="${req.body.username}"`;

connection.query(sql, (err, result) => {
    if(err) throw err;
    if(utils.duplicateChecker(result)) {
        return res.status(409).json({
            error: "Username Exist",
            code: 409
        });
    } else {
        hasher({password: req.body.password}, (err, pass, salt, hash) => {
            let user = {
                authId: 'local: '+req.body.username,
                username: req.body.username,
                password: hash,
                salt: salt,
                displayName: req.body.displayName
            };
    let sql = 'INSERT INTO users SET ?';
     connection.query(sql, user, (err, rows) => {
        if(err) {
            throw new Error("register error!");
        } else {
            req.login(user, (err) => {
                req.session.save(() => {
                                        return res.json({ success: true });
                });
            });
        }
    });
    });  
    }
}); 
});

正如您在上面所看到的,每次请求出错或完美时,json都包含错误&返回代码或成功属性。

我想要做的是通过angular2的http服务获取这些jsons。

@Injectable()
export class UserAuthenticationService {

  private loginUrl = "http://localhost:4200/auth/login";
  private registerSuccessUrl = "http://localhost:4200/auth/register";

  headers = new Headers({
    'Content-Type': 'application/json'
  });

  constructor(private http: Http) { }

  /*
    body: {
     username,
     password,
    }
  */
  logIn(user: Object) {
    return this.http
    .post(this.registerSuccessUrl, JSON.stringify(user),
    { headers: this.headers });
  }

我尝试过这种方式。使用后端网址发出http发布请求。 并在AuthComponent上实现函数。

export class AuthComponent {

  username: string = '';

  password: string = '';

  remembered: boolean = false;

  submitted = false;

  constructor(private userAuthenticationService: UserAuthenticationService) {}

  onsubmit() { 
    this.userAuthenticationService.logIn({ username: this.username, password:              this.password });
    this.submitted = true; 
  }
 }

但结果是我只是在屏幕上获得了json对象。 {success:true}!

如何通过http调用获取此json对象并使用'success'属性?

2 个答案:

答案 0 :(得分:1)

Http调用是异步的。因此,使用类似的东西:  const data =this.userAuthenticationService.logIn({ username: this.username, password: this.password });不起作用。而是相应地回应这样的反应:

this.userAuthenticationService.logIn({ username: this.username, password: this.password }).subscribe(
    data => {
      this.submitted = data.success; 
}); 

此处data是来自服务器的响应对象。

答案 1 :(得分:1)

使用服务器的响应。

  onsubmit() { 
     this.userAuthenticationService
        .logIn({ username: this.username, password: this.password })
        .subscribe(result => {
           //here check result.success
        }, error => console.error(error));
     this.submitted = true; 
      }