简体   繁体   English

angular2 http发布请求以获取res.json()

[英]angular2 http post request to get res.json()

I'm currently making simple user-authentication app. 我目前正在制作简单的用户身份验证应用。

now I'm done with backend process with node js and passport. 现在,我已经完成了节点js和passport的后端处理。

what I've done was returning json response if authentication goes well or not. 我所做的是,如果身份验证顺利进行,则返回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 });
                });
            });
        }
    });
    });  
    }
}); 
});

As you can see above, every time request makes error or goes perfect, json that contains error & code or success property is returned. 从上面可以看到,每次请求出错或变得完美时,都会返回包含error&code或success属性的json。

What I want to do is that getting these jsons via http service of angular2. 我想做的是通过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 });
  }

What I've tried is this way. 我尝试过的就是这种方式。 Make http post request using backend url. 使用后端网址发出http发布请求。 and implement function on AuthComponent. 并在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; 
  }
 }

But result is I just get json object on screen. 但是结果是我只是在屏幕上得到json对象。 { success: true }! {成功:正确}!

How can I get this json object thru http call and make use of 'success' property? 如何通过http调用获取此json对象并利用'success'属性?

The Http calls are asynchronous. Http调用是异步的。 Hence, using something like : const data =this.userAuthenticationService.logIn({ username: this.username, password: this.password }); 因此,使用类似const data =this.userAuthenticationService.logIn({ username: this.username, password: this.password }); would not work. 将无法正常工作。 Rather subcribe to the response like this : 而是订阅这样的响应:

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

Here data is the response object from the server. 这里的data是服务器的响应对象。

You are not using the server's response. 没有使用服务器的响应。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM