为HTTP请求确定范围

时间:2017-04-27 17:38:55

标签: javascript http vue.js

所以我希望变量pass_or_fail在.then子句中被赋予,并且该赋值将反映在.then子句之外

this.$http.post('http://localhost:3000/signup?username='+this.username+'&password='+this.password+'&password2='+this.password2)
  //make get request to API with what USER entered into the search bar in the query string
    .then(response => {
        if(response.body== "success"){

          this.pass_or_fail=response.body;

        }
    }

)

   console.log(this.pass_or_fail);
    if(this.pass_or_fail=="success"){
    this.$router.push({name:'landing-page'});
    }

  //set sources variable to our response


}

但是,当我在.then子句之外的console.log(this.pass_or_fail)时,该变量尚未分配给response.body。有关为什么.then子句中的更改没有反映在子句之外的任何想法?

2 个答案:

答案 0 :(得分:1)

帖子是异步请求,这意味着当您记录.env时,传递给this.pass_or_fail方法的函数尚未触发。

您需要根据传递给then的函数内部的post请求结果放置任何代码:

then()

答案 1 :(得分:1)

因为您仍在尝试同步获取this.pass_or_fail的值,但仍会获得结果。我想它会返回undefined。在使用之前,您需要“等待”响应。最简单的方法是在then回调中处理您的逻辑。如果您不想这样做,可以使用PromisesAsync/Await