Laravel接口返回true,Vue.js中Axios却始终获取false的问题
问题
数据库中存在对应数据,直接访问/posts/heart-status/1接口返回true,但在Vue组件的created()方法中调用该接口始终得到false。
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 } } };
解决方案
问题根源是Vue代码中模板字符串使用错误:你用单引号'包裹URL,导致${this.postId}没有被解析为实际的postId值,请求的URL变成了字面量/posts/heart-status/${this.postId},后端接收到无效的$postId,因此返回false。
修正步骤
将Axios请求中的单引号替换为反引号(`),让模板变量正确解析:
- 错误写法:
axios.get('/posts/heart-status/${this.postId}') - 正确写法:
axios.get(/posts/heart-status/${this.postId})
- 错误写法:
(可选)在catch块中打印请求的实际URL,方便排查参数问题:
.catch(function (error) { console.error('请求URL:', error.config.url); console.error(error); })
修正后的Vue关键代码片段
created(){ // 用反引号包裹URL,解析模板变量 axios.get(`/posts/heart-status/${this.postId}`) .then(response =>{ console.log(response.data.isHeart) this.isFilled = response.data.isHeart; }) .catch(function (error) { console.error('请求URL:', error.config.url); console.error(error); }) }, methods:{ checkHeartStatus(){ // 同样修正这里的URL axios.get(`/posts/heart-status/${this.postId}`) .then(response =>{ console.log(response.data.isHeart) this.isFilled = response.data.isHeart; }) .catch(function (error) { console.error('请求URL:', error.config.url); console.error(error); }) }, // 其他方法保持不变 }
内容的提问来源于stack exchange,提问作者Jay Fuego
相关产品推荐
相关产品推荐

