【问题标题】:angular2 http post request to get res.json()angular2 http post请求获取res.json()
【发布时间】:2017-10-07 14:12:52
【问题描述】:

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

现在我已经完成了使用节点 js 和护照的后端流程。

我所做的是返回 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 });
  }

我尝试过的就是这种方式。使用后端 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 对象并利用“成功”属性?

【问题讨论】:

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


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

    【讨论】:

    • 感谢您的建议,但我发现我做错了...我应该将包含用户名和密码的 json 发送到 url: '/auth/login' 以便后端处理身份验证过程。
    • 您仍然不应该使用您当前的方法。它确实有效,但您将无法处理来自 api 的响应。
    • 是的,这与我建议的方法相同。
    【解决方案2】:

    没有使用服务器的响应。

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

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 2016-05-14
      • 2017-03-12
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多