javascript - HTTP 请求的范围

标签 javascript http vue.js

所以我希望变量 pass_or_fail 在 .then 子句内部分配,并且该分配反射(reflect)在 .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 子句内部的更改没有反射(reflect)在子句外部吗?

最佳答案

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

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

this.$http.post('yoururl')
  .then((response) => {
    if (response.body == "success") {
      this.pass_or_fail = response.body;

      console.log(this.pass_or_fail);

      this.$router.push({ name: 'landing-page' });
    }
  });

关于javascript - HTTP 请求的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664532/

相关文章:

javascript - 使用 jQuery,如何检查表格单元格是否为空?

php - 通过 HTTP GET 传递带键的数组

http - IIS 7.5 似乎没有使用动态压缩

javascript - 模拟 vue 组件依赖

laravel - Vue.js 在特定元素上添加类

javascript - Matlab 中/... 是什么意思?

javascript - 返回上一页相同的滚动位置,并使用 jquery 在页面上延迟加载图像

javascript - HTML2PDF自动打印

rest - PUT 是否应该始终能够插入?

reactjs - React.js 是否有类似 Vue.js 的修饰符 "v-model.lazy"