Vue3使用axios发PATCH请求到CodeIgniter3 REST服务参数为空怎么解决
PATCH请求form-data参数无法解析问题解决方案
PHP原生仅会自动解析POST请求的multipart/form-data格式数据,PATCH、PUT等请求的同类格式数据不会被自动拆分存入全局变量,你使用的chriskacerguis/codeigniter-restserver扩展默认没有适配这类场景,所以只能拿到未解析的原始请求体内容,无法通过$this->patch()直接取到对应字段值。可选择以下两种方案解决:
方案1:前端调整请求格式(改造成本最低)
直接放弃传formData格式,改用JSON格式传参,axios默认对JSON请求的处理逻辑完善,后端rest库也能正常解析JSON格式的PATCH参数,无需额外修改后端代码。
修改后前端代码如下:
updateUser(){ // 无需转为formData,直接传对象即可,axios会自动转为JSON并添加对应请求头 axios.patch('http://localhost/rest-server/api/user', app.currentUser).then(function(response){ app.currentUser ={}; if(!response.data.status){ app.errorMsg = response.data.message; } else { app.successMsg = response.data.message; app.getUsers(); } }); }
修改后后端原有逻辑无需变动,$this->patch('id')即可正常获取到参数值。
方案2:后端兼容form-data格式PATCH请求(适用于必须传formData的场景,如带文件上传的请求)
如果业务要求必须用formData格式传参,可手动在接口逻辑前添加PATCH请求的multipart数据解析逻辑,代码如下:
public function index_patch() { // 手动解析multipart/form-data格式的PATCH请求参数 if (strpos($this->input->server('CONTENT_TYPE'), 'multipart/form-data') !== false) { $rawInput = file_get_contents('php://input'); $boundary = substr($rawInput, 0, strpos($rawInput, "\r\n")); $parts = array_slice(explode($boundary, $rawInput), 1, -1); $patchData = []; foreach ($parts as $part) { $part = trim($part); if (empty($part)) continue; list($header, $body) = explode("\r\n\r\n", $part, 2); if (preg_match('/name="([^"]+)"/', $header, $matches)) { $patchData[$matches[1]] = $body; } } // 将解析好的参数合并到rest库的PATCH参数容器中 $this->_patch_args = array_merge($this->_patch_args, $patchData); } // 原有业务逻辑保持不变 $id = $this->patch('id'); $data = [ 'first_name' => $this->patch('first_name'), 'last_name' => $this->patch('last_name') ]; if ($this->user_model->updateUser($data, $id) > 0) { $this->response([ 'status' => true, 'message' => 'User updated successfully.' ], REST_Controller::HTTP_NO_CONTENT); } else { $this->response([ 'status' => false, 'message' => 'Failed to update.' ], REST_Controller::HTTP_BAD_REQUEST); } }
注意:如果需要处理文件上传场景,上述解析逻辑还需要额外适配文件部分的解析规则。
内容的提问来源于stack exchange,提问作者owf
相关产品推荐
相关产品推荐

