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

Postman无法读取数据但Axios正常的PHP API问题求助

解决Axios与Postman请求PHP后端的数据兼容读取问题

问题核心

你的问题本质是Axios和Postman默认发送请求的Content-Type格式不同,导致PHP的两种数据读取方式无法同时兼容:

  • Axios默认以application/json格式发送数据,这类数据PHP不会自动解析到$_POST,只能通过php://input读取后JSON解码。
  • Postman用form-data/x-www-form-urlencoded发送时,Content-Type对应multipart/form-data或application/x-www-form-urlencoded,PHP会自动解析到$_POST,但此时php://input的内容不是JSON格式,直接json_decode会得到null,导致无返回。

另外你的PHP代码存在两处小错误:

  1. 拼写错误:Access-Contro-Allow-Headers少了一个l,应该是Access-Control-Allow-Headers。
  2. 语法错误:print_r($data json_decode(...))缺少赋值和连接符,正确写法是$data = json_decode(...); print_r($data);。

解决方案:统一兼容两种请求格式

编写一个通用的请求数据获取逻辑,自动识别请求的Content-Type,分别处理JSON和表单格式的数据:

修正后的PHP代码

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 通用获取请求数据函数
function getRequestData() {
    $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
    
    // 处理JSON格式请求(Axios默认发送)
    if (strpos($contentType, 'application/json') !== false) {
        $rawData = file_get_contents('php://input');
        return json_decode($rawData, true); // 转为关联数组,和$_POST格式一致
    }
    
    // 处理表单格式请求(Postman的form-data/x-www-form-urlencoded)
    return $_POST;
}

// 获取请求数据
$requestData = getRequestData();

// 验证数据是否存在
if (!isset($requestData['email'])) {
    echo json_encode(['error' => 'email参数缺失']);
    exit;
}

// 返回数据示例
echo json_encode([
    'status' => 'success',
    'email' => $requestData['email'],
    'achternaam' => $requestData['achternaam'] ?? '未提供'
]);

Axios代码(无需修改)

let fdata = {
  email: "testemail",
  achternaam: "testachternaam",
};

axios
  .post("http://localhost/api/test", fdata)
  .then((result)=>{
    console.log(result.data)
})

测试验证

  1. Axios请求:直接运行原有代码,后端会自动识别JSON格式,正确返回数据。
  2. Postman请求:
    • 方式一:选择Body -> raw -> JSON,输入和Axios相同的JSON数据发送,后端正常解析。
    • 方式二:选择Body -> x-www-form-urlencoded,添加email和achternaam键值对发送,后端同样能正确获取数据。

这样无论用Axios还是Postman测试,都无需修改后端代码,完美兼容两种场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:07:24