You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel API接收Axios FormData返回空值问题求助

Laravel后端接收不到Node.js Axios提交的FormData数据问题

之前正常运行的Node.js用户数据上传脚本,今天未修改任何代码,却出现Laravel后端接收不到输入值的情况,API接口返回data: []空数组,说明数据未成功传递到后端。

依赖引入代码

const axios = require('axios');
const download = require('image-downloader');
const fs = require('fs');
const FormData = require('form-data');

API提交函数

async function post_in_api(api_data) {
    try {
        const form = new FormData();
        for (let key in api_data) {
            if (key !== 'photos') {
                form.append(key, api_data[key]);
            }
        }

        // Post the form data to the API
        const response = await axios.post('https://mylaravelbackend.com/api/register_independent_user', form, {
            headers: form.getHeaders(),

        });

        console.log(response);
        // console.log('Data posted successfully');
    } catch (error) {
        console.log(error);
    }
}

传入的api_data示例

{
   full_name: escrt.full_name,
   email: `${escrt.full_name}${random_number}@email.com`,
   phone_number: escrt.phone_number,
   display_name: escrt.full_name,
   age: escrt.age,
   nationality: escrt.nationality,
   ethnicity: escrt.ethnicity,
   ...
}

Laravel控制器代码

// register independent escrt
public function register_independent_escrt(Request $request){
    return $request->all();
    ...
}

排查与解决建议

  • 确认FormData内容:在append数据后,添加代码打印FormData的键值对,检查是否所有预期字段都正确添加:
    for (let pair of form.entries()) {
        console.log(`${pair[0]}: ${pair[1]}`);
    }
    
  • 验证请求头:手动合并FormData的头信息,避免Axios自动覆盖,修改请求配置:
    const response = await axios.post('https://mylaravelbackend.com/api/register_independent_user', form, {
        headers: {
            ...form.getHeaders(),
            // 可额外添加其他必要头信息
        }
    });
    
  • 检查Laravel CSRF配置:确认API路由是否在api中间件组下(默认Laravel的api路由不启用CSRF验证),如果手动给API路由加了web中间件,会触发CSRF验证导致数据被拦截。
  • 查看实际请求内容:用Axios拦截器打印请求的完整body,确认数据是否真的发送到后端:
    axios.interceptors.request.use(config => {
        console.log('Request data:', config.data);
        return config;
    });
    
  • 过滤空值字段:在FormData append前判断字段值是否有效,避免添加undefined或null值:
    for (let key in api_data) {
        if (key !== 'photos' && api_data[key] != null) {
            form.append(key, api_data[key]);
        }
    }
    
  • 检查Laravel路由与中间件:确认路由是否正确指向控制器方法,有没有全局中间件对请求参数做了过滤或修改。

内容的提问来源于stack exchange,提问作者Arnob Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 01:03:28