首页 > 解决方案 > 带有 HTTP PUT 的 JavaScript Fetch() 未将 FormData 发送到 PHP 服务器

问题描述

我正在使用 PHP REST API 将数据从 JS 客户端发布到 PHP 8 服务器。我正在使用JSfetch()方法。当使用POSTformdata 被发送到 PHP 的全局 $_POST,但由于我需要更新数据我必须使用PUT. 不知何故,谷歌浏览器没有将表单数据发送到服务器,我不知道为什么。有人知道原因吗?

JS:

常量 formData = new FormData();
formData.append('title', 'Hello world');

常量选项 = {
    方法:'PUT',
    正文:JSON.stringify(formData);
    缓存:'无缓存',
    模式:'cors',
    凭据:'同源',
    重定向:'关注',
    推荐人:'无推荐人',
    
    // 也不工作
    // 标题:{
    // '内容类型': 'application/json; 字符集=UTF-8;'
    // },
};

fetch('/some/api/v1', 选项);
PHP 8 服务器:

var_dump($_REQUEST); // 无效的

标签: javascriptphpfetchput

解决方案


问题不在客户端,而在服务器。Firefox 和 Chrome 都将数据序列化并使用以下代码发送:

document.getElementById('myForm').addEventListener('submit', function(e){
            e.preventDefault();
            let fd = new FormData(this);
            fetch('test.php', {method:'PUT', body:fd})
            .then(function(response){
                response.text().then(function(txt){console.log("Response:"+txt);});
            });
        });

问题在于 PHP 对 的支持PUT,它不会自动为您解包数据。您可以从stdin流中获取它。

/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
while ($data = fread($putdata, 1024)) {
    echo $data;
}

回复:

-----------------------------256278305409917102757952731 
Content-Disposition: form-data; 
name="myText" ffsssssdd 
-----------------------------256278305409917102757952731-- 

如果要将表单数据作为 JSON 对象发送,可以使用:

const serialize_form = form => JSON.stringify(
    Array.from(new FormData(form).entries())
        .reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
        );
           
const json = serialize_form(this);
fetch('test.php', {method:'PUT', body:json, headers:{'content-type':'application/json'}})
    .then(function(response){
         response.text().then(function(txt){console.log("Response:"+txt);});
                });

回复:

{"myText":"ghfghfghfg"}

serialize_form这个答案中获取的功能

请参阅PHP 参考


推荐阅读