获取请求状态最佳实践

时间:2018-01-31 09:03:25

标签: node.js angular httprequest

在我的Node.js后端,我曾经在我的回复中添加一个布尔值来检查一切是否正常:

if(req.body.user.username == null || req.body.user.username == '' || req.body.user.password == null || req.body.user.password == '' || req.body.user.email == null || req.body.user.email == ''){
    res.json({success: false, message: 'Ensure username, email and password provided.'});
  }else{
    user.save((err) => {
      if(err) {
        res.json({success: false, message: 'Username or Email already exists.'});
      }else{
        res.json({success: true, message: 'User created!',user :user});
      }
    });
  }

然后,在我的前面检查这个变量:

userRegister(body) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this._http.post("/api/register", body, options).map((res: Response) => res.json())
  }

 register(){
    //make JSON body
    let body = JSON.stringify({"user" : this.registeredUser})
    // Access the USER Service's Auth() method we defined
    this._userService.userRegister(body).subscribe((res) => {
      console.log(res);
      if(res.success){
        //gotoprofile
      }
    }
 }

我被告知这是一个不好的做法,我可以获得响应状态代码。我不想使用Observables或Promises,因为这意味着我将不得不再次实施每个请求。

我试图获得这样的状态:

return this._http.post("/api/register", body, options).map((res: Response, status) => res.json())

但它不起作用..

1 个答案:

答案 0 :(得分:0)

如您的代码中所示,它是已发布的请求。您可以使用以下标准状态代码。

if(req.body.user.username == null || req.body.user.username == '' || req.body.user.password == null || req.body.user.password == '' || req.body.user.email == null || req.body.user.email == ''){
    res.status(400).json({success: false, message: 'Ensure username, email and password provided.',reason:"Bad Request"});
  }else{
    user.save((err) => {
      if(err) {
        res.status(409).json({success: false, message: 'Username or Email already exists.',reason:"Conflict"});
      }else{
        res.status(201).json({success: true, message: 'User created!',user :user});
      }
    });
  }