简体   繁体   中英

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.

what I've done was returning json response if authentication goes well or not.

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.

What I want to do is that getting these jsons via http service of angular2.

@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. and implement function on 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. { success: true }!

How can I get this json object thru http call and make use of 'success' property?

The Http calls are asynchronous. Hence, using something like : 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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