Laravel修改Content-Type为multipart/form-data后出现404 Not Found问题
Laravel中multipart/form-data请求返回404的解决办法
问题原因
你手动设置了Content-Type: multipart/form-data,但multipart请求需要自动生成的boundary分隔符来区分表单字段,手动设置的头里没有这个关键内容,导致目标服务器无法正确解析请求,最终返回404。Laravel的Http客户端会自动处理multipart请求的Content-Type(包括生成boundary),完全不需要手动指定。
修复步骤
- 从自定义请求头中移除
Content-Type字段,交给Http客户端自动处理 - 如果请求包含文件,使用
attach()方法添加文件;如果只是普通表单数据,直接传递数组即可
修改后的代码
public function customHeaders() { return [ 'Authorization' => request()->header('Authorization'), 'Access-Control-Allow-Credentials' => true, ]; } public function post(Request $request) { $httpClient = Http::withHeaders($this->customHeaders()); // 若需上传文件,用attach方法添加(示例) // $httpClient->attach('file', $request->file('file')->getRealPath(), $request->file('file')->getClientOriginalName()); $response = $httpClient->post($this->url, $request->all()); return response()->json($response->json(), $response->status()); }
补充说明
如果目标服务器严格要求multipart/form-data格式,只要你传递的是数组(或包含文件对象),Laravel Http客户端会自动设置正确的Content-Type: multipart/form-data; boundary=xxx请求头,手动设置反而会破坏请求结构,导致服务器无法识别。
内容的提问来源于stack exchange,提问作者toffeegz
相关产品推荐
相关产品推荐

