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

Vue Axios向PHP传递Person数据时出现Undefined array key错误

解决Axios POST请求PHP无法读取Person字段的问题

你遇到的问题是:Axios发送POST请求返回200状态码,但PHP无法通过$_POST['Person']获取数据,报错Undefined array key "Person"。核心原因是虽然你设置了Content-Type: application/x-www-form-urlencoded,但Axios默认会把JS对象序列化为JSON格式,而非PHP能识别的表单键值对格式。另外你的PHP代码存在重复跨域头的问题,也需要修正。


修复Vue端请求数据格式

以下两种方法任选其一,确保请求数据是PHP可解析的表单格式:

方法1:使用URLSearchParams转换数据

const Pagedata = {
    Person: "Youmna",
};

// 将对象转为表单键值对格式
const formData = new URLSearchParams();
for (const key in Pagedata) {
    formData.append(key, Pagedata[key]);
}

const options = {
    method: 'POST',
    url: 'http://localhost/linktree-vue/linktree-Create-Page.php',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: formData // 传入转换后的表单数据
};

axios.request(options)
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error(error);
    });

方法2:用qs库序列化数据(Vue项目通常自带)

如果项目已引入qs库,可直接用它快速序列化对象:

import qs from 'qs'; // 未全局引入时需手动导入

const Pagedata = {
    Person: "Youmna",
};

const options = {
    method: 'POST',
    url: 'http://localhost/linktree-vue/linktree-Create-Page.php',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify(Pagedata) // 序列化表单数据
};

axios.request(options)
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error(error);
    });

修正PHP代码的两个问题

  1. 移除重复的Access-Control-Allow-Origin头,仅保留一个即可
  2. 增加字段存在性判断,避免触发警告:
header('Content-Type: application/json');
// 按需保留一个跨域头,优先指定具体域名而非通配符
header("Access-Control-Allow-Origin: http://localhost:8080");

// 先判断字段是否存在,再读取值
$PersonName = isset($_POST['Person']) ? $_POST['Person'] : null;
echo json_encode($PersonName);

内容的提问来源于stack exchange,提问作者Ahmed Khaled El-Dakhly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:13:16