【问题标题】:Why I am not receiving data at server end by sending axios.put request为什么我没有通过发送 axios.put 请求在服务器端接收数据
【发布时间】:2019-06-13 10:53:16
【问题描述】:

我在 reactjs.Axios.get 中使用 Axios Api 对我来说工作正常,但我遇到了 axios.put 的问题,当我使用简单对象发送请求时,我得到了正确的响应,但是当我发送请求表单数据时,我得到了响应为空。

当我使用工作正常的简单对象发送请求时:

  const data= {ProductName:"Dummy"};
const apiurl = `http://localhost/testapi/index.php/api/products/product`;
axios.put(apiurl, data).then(response => {
  console.log(response.data);
});

服务器端:

 public function product_post()
{
    $data = array();
    $data['ProductName'] = $this->post('ProductName');
    $this->response(
        [
            'status' => "ok",
            'message' => "Data inserted successfully",
            'info' => $data['ProductName']
        ],
        REST_Controller::HTTP_OK
    );
}

我得到的正确答案是“Dummy”

当我使用无法正常工作的 Formdata 发送请求时:

  var data= new FormData();
data.set("ProductName","Dummy");
const apiurl = `http://localhost/testapi/index.php/api/products/product`;
await axios.put(apiurl, data).then(response => {
  console.log(response.data);
});

服务器端:

 public function product_post()
{
    $data = array();
    $data['ProductName'] = $this->post('ProductName');
    $this->response(
        [
            'status' => "ok",
            'message' => "Data inserted successfully",
            'info' => $data['ProductName']
        ],
        REST_Controller::HTTP_OK
    );
}

现在我收到的 $data['ProductName'] 响应为空。 还有一件事,我还尝试使用 formdata 发送文件,但得到了 null

请告诉我代码有什么问题。

【问题讨论】:

    标签: php reactjs web-services axios


    【解决方案1】:

    您需要使用 append 方法向 FormData 添加新的键和值

    改变

      data.set("ProductName","Dummy");
    

      data.append("ProductName","Dummy");
    

    编辑:

    您需要在标题中指定要发送 FormData,因为该内容类型应该是 multipart/form-data。试试下面的代码

       var data= new FormData();
         data.append("ProductName","Dummy");
         const config = {     
             headers: { 'content-type': 'multipart/form-data' }
         }
         const apiurl = `http://localhost/testapi/index.php/api/products/product`;
        await axios.put(apiurl, data, config).then(response => {
           console.log(response.data);
        });
    

    【讨论】:

    • 我尝试追加而不是设置我不起作用我得到了相同的响应:{状态:“ok”,消息:“数据插入成功”,信息:null}
    • @Ch Mudabbir 嗯。我更新了我的答案,请检查编辑部分
    • 实际上 axios.post 工作正常,但是当我使用 axios.put 时它不起作用
    • 只需更改帖子以将其与我编辑的答案一起使用
    猜你喜欢
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多