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

angular2 http post request to get res.json()

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

现在我已经完成了 node 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服务获取这些json。

@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 });
  }

我试过的就是这种方式。使用后端 url 发出 http post 请求。 并在 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 对象。 {成功:真}!

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

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是来自服务器的响应对象。

没有使用服务器的响应。

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