【问题标题】:Axios doenst send formData in put methodAxios 不会在 put 方法中发送表单数据
【发布时间】:2021-10-16 15:17:21
【问题描述】:

我正在尝试更新用户的个人资料(社交网络应用程序),我将 React 作为前端,将 laravel 作为后端。数据包括一个图像,所以我使用 FormData 发送它,我在后端做一个小的验证以检查数据是否发送到后端,但我发现 axios 没有发送 formData。 这是我在提交后运行的函数:

const editProfile = (e) => {
        e.preventDefault()
        setLoading(true)
        const formData = new FormData();
        formData.append('avatar', pic.avatar)
        formData.append('website', profile.website)
        formData.append('addresse', profile.addresse)
        formData.append('bio', profile.bio)
        formData.append('phone', profile.phone)
        formData.append('gender', profile.gender)
        formData.append('full_name', auth.full_name)
        formData.append('user_name', auth.user_name)
        formData.append('email', auth.email)
        console.log(formData)
            axios.put(`api/profile/update/${id}`, formData).then((res) => {
                if(res.data.success) {
                    console.log('success')
                    history.push(`/profile/${id}`)
                }else {
                    console.log(res.data.message)
                    setLoading(false)
                }
            })      
    }

我只在 laravel 中设置了性别:

public function update(Request $request, $id)
    {
        $profile = Profile::find($id);
        if(is_null($profile)) {
            return response()->json([
                'success' => false,
                'message' => 'Profile can not be found!'
            ]);
        }else {
            $validate = Validator::make($request->all(),[
                'gender' => 'required'
            ]);
            if($validate->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validate->messages()
                ]);
            }else {...

正如它在反应逻辑中提到的,如果响应失败,我正在执行 console.log 来检查错误,并且我需要获取性别字段,我之前尝试过执行 console.log(profile.gender)向 axios 发送数据,我可以正常看到值, 那么有人可以帮帮我吗?

【问题讨论】:

  • 如果您在服务器端收到任何内容,请尝试 dd $request 对象。我认为 axios 没有发送您的表单数据对象。
  • 当我使用 react 结构时,如何查看 dd 的结果?
  • 它将在 api 响应中可见。或者,如果您使用的是邮递员,它将在那里可见。
  • 在您的开发者工具中,在网络中,转到您的请求并检查预览,您将看到dd 输出。

标签: reactjs laravel axios


【解决方案1】:

我认为您应该更改标题 例如

 .put(url, formData, {
        headers: { "Content-type": "multipart/form-data" },
      })

【讨论】:

    【解决方案2】:

    我解决了问题, 解决方案:我必须将方法从 put 更改为 Post(在 laravel 路由和 react axios 中)。

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      相关资源
      最近更新 更多