我构建了带有文件上载的自定义React/Gatsby多部分表单,我想将所有表单数据发送到WordPress端点,将文件上载到特定文件夹,并在WordPress后端显示所有数据。
这是我发送数据的方式:
const {
stepOne,
stepTwo,
} = useContext(FormStepProvider)
const steps = {
stepOne: stepOne,
stepTwo: stepTwo,
}
const postData = async () => {
const formData = new FormData()
formData.append("stepOne", JSON.stringify(stepOne))
formData.append("stepTwo", stepTwo.file)
await fetch("https://panel.domain.com/wp-json/test/v1/forms", {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: formData,
})
.then(response => response)
.then(result => {
console.log("Success:", result)
})
.catch(error => {
console.error("Error:", error)
})
}
useEffect(() => {
postData()
console.log(steps)
}, [])
这是我得到的回应:
这是我的端点:
add_action( \'rest_api_init\', function () {
register_rest_route( \'test/v1\', \'forms\', array(
\'methods\' => \'POST\',
\'callback\' => \'get_formdata_function\',
\'args\' => array(),
) );
} );
function get_formdata_function(WP_REST_Request $request)
{
$data = $request->get_body();
print_r($data);
}
我是WordPress的新手,我想知道做这件事的最好方法是什么?