【问题标题】:Axios is sending array instead of json object in post requestAxios 在 post 请求中发送数组而不是 json 对象
【发布时间】:2021-03-16 06:50:29
【问题描述】:

我正在尝试使用 axios 从 Vuejs 前端向后端的 Laravel 发送一个发布请求。

const data = {
            file: {id}
        }

        axios.post('api/documents/remove', data).then((response) => {
                console.log(response.data);
            }
        }).catch(err => { console.log(err.response.data); })

在 laravel 中,我正在打印这样的请求,

 public function removeFile(Request $request)
 { 
    dd($request);
 }

这是我的输出。

Illuminate\Http\Request {#51
  #json: Symfony\Component\HttpFoundation\ParameterBag {#43
  #parameters: array:8 [
  "file" => array:1 [
    "id" => 61
  ]
}

【问题讨论】:

  • 这是预期的行为。您可以访问 $request 对象 Laravel 文档中的数据:laravel.com/docs/8.x/requests#retrieving-input
  • 你应该看看 JavaScript 对象如何与 php 反应
  • AJAX 请求需要 (json) 字符串。只需返回响应return response()->json($request->all(), 200);。

标签: javascript php laravel vue.js


【解决方案1】:

PHP 的“arrays”并不是真正的数组,它们是有序映射。这就是您的输出显示的内容,请求包含参数,这是一个有序映射,file 参数是一个有序映射,其中包含id => 61。在 JavaScript 中,这将是一个对象(或 Map,有时);在许多其他语言中,它将是某种地图或字典。 PHP 称它们为数组。

无论哪种方式,如果您访问file 参数(我不“做” Laravel,所以我不知道您是如何做到的),您可以像这样从中获取id:$file[ id]。查看Laravel docs,看起来会是:

$file = $request->input('file');
$id = $file['id'];

【讨论】:

  • 之前我访问文件数组中的项目,如$request->file->id 现在它显示错误Trying to get property 'id' of non-object
  • @Abhimanu - 这不是从 PHP 关联数组中获取条目值的方式,而是获取对象属性值的方式。它们是不同的东西。我没有使用 Laravel(很多或最近),所以我不知道其中的 $request->file 部分,但假设它是有效的(文档建议它是 $request->input('file') 但也许另一个是速记),你会想要$request->file['id']。不过,要再次明确:这是 PHP 的事情,PHP 中如何处理“属性包”,而不是 Axios 的事情。
【解决方案2】:

可以得到$request的数据

$file = $request->input('file');
$file['id'];

//Or

$fileId = $request->input('file.id');

【讨论】:

  • 我想像$request->file->id一样访问它,现在它显示错误Trying to get property 'id' of non-object
  • 显然它会抛出一个错误$request->file or $request->input('file') is an array can't access it elements with object notation。已在答案中展示了访问id 的可能方式
【解决方案3】:

请求$request是传递数组而不是对象实例,所以,你只能像下面这样访问:

$request->input('file')['id']

或者

$request->file['id']

或者

$request->input('file.id')

或者,只有文件字段

$request-all()[0]['file']['id']

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多