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

React Native用户添加表单提交异常:后端接收字段为空求助

问题解决:React Native提交表单后端接收不到字段

问题原因

后端通过$_POST获取表单参数,但前端请求的数据格式与后端预期不匹配:

  1. 前端handleAddNewUser中创建了FormData,但传给apiService.addUser后,被错误地用JSON.stringify()转为JSON字符串发送,且设置了Content-Type: application/json
  2. PHP的$_POST仅能解析application/x-www-form-urlencoded或multipart/form-data格式的请求,无法直接读取JSON格式的请求体,导致所有字段为空

解决方案1:保持表单数据格式(推荐,与原有网站后端兼容)

步骤1:修改API服务的addUser方法

直接传递FormData,不手动设置Content-Type(浏览器会自动添加正确的multipart/form-data请求头):

addUser: async (formData) => {
    try {
        const response = await fetch(`${BASE_URL}/users/addUsers`, {
            method: 'POST',
            body: formData // 直接传递FormData,无需JSON转换
        });

        if (!response.ok) {
            throw new Error(`HTTP状态码:${response.status}`);
        }

        const responseData = await response.json();
        console.log('用户添加成功', responseData.message);
        return responseData;
    } catch (error) {
        console.error('API请求出错:', error.message);
        throw error;
    }
},

步骤2:前端handleAddNewUser保持现有逻辑

现有代码中创建FormData的逻辑正确,无需修改:

const handleAddNewUser = async (event) => {
    event.preventDefault();

    console.log(newUser);
        
    const formData = new FormData();
    for (const key in newUser) {
        formData.append(key, newUser[key]);
    }

    try {
        const addUserResponse = await apiService.addUser(formData);
        console.log('API响应:', addUserResponse);
        
        if (addUserResponse.success) {
            console.log('用户添加成功', addUserResponse.message);
            setNewUser({ firstname: '', lastname: '', email: '', tel: '', address: '', role: 'User' });
            const fetchedUsers = await apiService.getAllUsers();
            setUsers(fetchedUsers);
        } else {
            const fetchedUsers = await apiService.getAllUsers();
            setUsers(fetchedUsers);
            console.error('用户添加失败:', addUserResponse.message);
        }
    } catch (error) {
        const fetchedUsers = await apiService.getAllUsers();
        setUsers(fetchedUsers);
        console.error('API请求出错:', error);
    }
};

解决方案2:修改后端支持JSON格式请求

如果希望前端发送JSON数据,调整后端代码解析请求体:

步骤1:修改后端addUser方法

public function addUser()
{
    $response = array();

    // 解析JSON格式的请求体
    $input = json_decode(file_get_contents('php://input'), true);
    
    $firstname = $input['firstname'] ?? null;
    $lastname = $input['lastname'] ?? null;
    $email = $input['email'] ?? null;
    $password = $input['password'] ?? null;
    $tel = $input['tel'] ?? null;
    $address = $input['address'] ?? null;
    $role = $input['role'] ?? null;

    // 初始化缺失字段数组
    $missingFields = array();

    // 检查必填字段逻辑不变...

    if (!empty($missingFields)) {
        $response['success'] = false;
        $response['message'] = '缺少字段:' . implode(', ', $missingFields) . '。';
        echo json_encode($response);
        return;
    }

    if ($this->userModel->emailExists($email)) {
        $response['success'] = false;
        $response['message'] = '错误:该邮箱已被使用。';
    } else {
        $this->userModel->addUser($firstname, $lastname, $email, $password, $tel, $address, $role);
        $response['success'] = true;
        $response['message'] = '用户添加成功。';
    }

    header('Content-Type: application/json');
    echo json_encode($response);
}

步骤2:调整前端代码

无需创建FormData,直接传递newUser对象:

const handleAddNewUser = async (event) => {
    event.preventDefault();

    console.log(newUser);

    try {
        const addUserResponse = await apiService.addUser(newUser);
        console.log('API响应:', addUserResponse);
        
        if (addUserResponse.success) {
            console.log('用户添加成功', addUserResponse.message);
            setNewUser({ firstname: '', lastname: '', email: '', tel: '', address: '', role: 'User' });
            const fetchedUsers = await apiService.getAllUsers();
            setUsers(fetchedUsers);
        } else {
            const fetchedUsers = await apiService.getAllUsers();
            setUsers(fetchedUsers);
            console.error('用户添加失败:', addUserResponse.message);
        }
    } catch (error) {
        const fetchedUsers = await apiService.getAllUsers();
        setUsers(fetchedUsers);
        console.error('API请求出错:', error);
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:44:52