You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义Laravel API的JSON响应并在Vuex中接收处理数据

问题修复方案

你遇到的两个问题均为语法使用错误导致,具体修复如下:

1. Laravel接口代码错误修复

原有代码存在4处核心错误:

  • response()->json() 方法的第二个参数才是状态码,你将状态码写入了第一个响应数据数组中,导致状态码始终使用默认值200
  • 查询Speler数据时仅构建了查询器,没有调用first()获取实际模型实例,返回的是查询构造器对象而非玩家数据
  • 创建Speler时,create()方法本身已经返回新创建的模型实例,后续多余的->first()和多余括号属于语法错误
  • 新增玩家成功时直接返回模型,默认状态码为200,不符合你前端判断的201逻辑
    修复后代码:
public function store(Request $request)
{ 
    if (Game::where('id',$request['game_id'])->exists() ){
        if (!Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->exists()){
            $newSpeler = Speler::create([                
                'name' => $request['name'],
                'pass_code' => $request['pass_code'],
                'game_id' => $request['game_id']
            ]);
            return response()->json($newSpeler, 201);
        }     
        elseif (Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code'])->exists()){
            $speler = Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code'])->first();
            return response()->json(['speler'=> $speler], 202);
        }           
        return response()->json(['status' => 'This name is already used, pass-code is not correct'], 409);
    }            
    return response()->json([ 'status' => 'The game-pin does not exist'], 403); 
}

2. Vuex Action代码错误修复

原有代码的核心问题是:fetch API返回的Response对象不能直接读取data属性,需要先调用json()方法解析响应体内容。
修复后代码:

export const addSpeler = ({commit}, formData) => {
    return new Promise((resolve, reject) => {         
        fetch(`api/speler`, {
            method: 'post',
            body:formData,
        })
        .then(async res => { 
            const resData = await res.json();
            if (res.status === 202){
                commit('SET_CURRENT_SPELER', resData.speler);
                resolve('De speler is succesfully logged on');
            }
            else if (res.status === 201){
                commit('SET_CURRENT_SPELER', resData);
                resolve('De speler is succesfully added')
            }
            else {
               reject(resData.status || 'De speler is not logged in. Name exists and does not match passcode');
            }
        })
        .catch(err => {
            reject(err.message)
        });
    })
} 

其他说明

修改完成后即可正常返回对应状态码,且前端可以正常拿到玩家数据存入Vuex。

内容的提问来源于stack exchange,提问作者M.Koops

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:45:03