首页 > 解决方案 > 使用 axios 将方法修补到 Codeigniter 3

问题描述

我在 vue 3 中遇到了问题 qith“补丁”方法

这是我的前端 vue js 脚本:

updateUser(){
  var formData = app.toFormData(app.currentUser);
  axios.patch('http://localhost/rest-server/api/user', formData).then(function(response){
    app.currentUser ={};
    if(!response.data.status){
      app.errorMsg = response.data.message;
    } else {
      app.successMsg = response.data.message;
      app.getUsers();
    }
  });
}

和我的后端codeigniter 3(顺便说一句,我从这里https://github.com/chriskacerguis/codeigniter-restserver使用休息服务器库 :

    public function index_patch()
    {
        $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);
        }
    }

但它不起作用,当我尝试回显 $id 时,它为空。

编辑,尝试打印$this->patch(),并得到以下结果:

Array
(
    [------WebKitFormBoundary4IqCBGyVSGTaLv6P
Content-Disposition:_form-data;_name] => "id"

7
------WebKitFormBoundary4IqCBGyVSGTaLv6P
Content-Disposition: form-data; name="first_name"

Brilian
------WebKitFormBoundary4IqCBGyVSGTaLv6P
Content-Disposition: form-data; name="last_name"

Aldamaa
------WebKitFormBoundary4IqCBGyVSGTaLv6P
Content-Disposition: form-data; name="created_at"

2021-05-18 08:56:16
------WebKitFormBoundary4IqCBGyVSGTaLv6P
Content-Disposition: form-data; name="updated_at"

2021-05-18 08:57:34
------WebKitFormBoundary4IqCBGyVSGTaLv6P--

)

我该如何解决这个问题?

标签: phpapivue.js

解决方案


当您使用此库中的补丁方法时,您必须发送 JSON 而不是表单数据作为请求的正文。因为这个库是为 REST 准备的,标准的通信形式是 JSON。


推荐阅读