Laravel-vue.js内axios中的错误响应

4zcjmb1e  于 2023-02-12  发布在  iOS
关注(0)|答案(1)|浏览(123)

这是我的Laravel控制器代码

public function show($postId){
        $reaction = Reaction::where([
            'post_id' => $postId,
            'user_id' => auth()->id(),
            ])->first();    
        
    if ($reaction) {
        return response()->json(['isHeart' => true]);
    } else {
        return response()->json(['isHeart' => false]);
    }
        
       
}

下面是我的Vue.js代码

axios.defaults.headers.common['X-CSRF-TOKEN'] = document.head.querySelector('meta[name="csrf-token"]').content;
export default{
    data(){
        return{
            isFilled:false,
            isHeart:false,
        };
    },
    created(){
        axios.get('/posts/heart-status/${this.postId}')
        .then(response =>{
            console.log(response.data.isHeart)
            this.isFilled = response.data.isHeart;
        })
        .catch(function (error) {
          console.error(error);
        })
    },
    methods:{
        toggleFill(){
            if(this.isFilled){
                this.unheart();
                this.isFilled = false;
            }else{
                this.heart();
                this.isFilled = true;
                this.isHeart = true
      setTimeout(() => {
        this.isHeart = false;
      }, 1000);
            }
        },
        checkHeartStatus(){
        axios.get('/posts/heart-status/${this.postId}')
        .then(response =>{
            console.log(response.data.isHeart)
            this.isFilled = response.data.isHeart;
        })
        .catch(function (error) {
          console.error(error);
        })
    },
        heart(){
            axios.post('/posts/heart',{
                post_id: this.postId,
            })
            .then(response =>{
                this.isFilled = true;
                this.isHeart = true
                console.log(response);
            })
            .catch(error =>{
                console.error(error);
            });
        },
        unheart(){
            axios.post('/posts/unheart',{
                post_id: this.postId
            })
            .then(response =>{
                this.isFilled = false;
                this.isHeart = false;
                console.log(response);
            })
            .catch(error =>{
                console.error(error);
            });
        }
    },
    props: {
        postId:{
            type: Number,
            required: true
        }
    }
};

</script>

所以我想得到一个response = true,在这段代码中,即使它有数据,它也总是返回false。
当我转到posts/heart-status/1时,它会给予我true,但在上面的代码中,使用方法created()时,它会给我false。

zpqajqem

zpqajqem1#

我已经知道这个问题了,我不使用单引号,而是使用反引号

created(){
        axios.get(`/posts/heart-status/${this.postId}`)
        .then(response =>{
            console.log(response.data.isHeart)
            this.isFilled = response.data.isHeart;
        })
        .catch(function (error) {
          console.error(error);
        })
    },

相关问题