我试图在React中获取一个调用,以便与我在MAMP上运行的PHP脚本进行对话。
由于某种原因,它给了我错误。.我不确定从这里到哪里。
这是我在React中使用的代码:
getPHP = () => {
var formData = new FormData();
formData.append('content', 'test2');
fetch(`http://localhost:8888/phpBackend/demo.php`, {
method: 'POST',
headers: {
},
body: formData,
}).then(res => res.json())
.then(response => {
console.log('response:');
console.log(response);
});
}
onSubmit = (e) => {
e.preventDefault();
this.getPHP();
}
还有我的PHP脚本:
<?php
$content = $_POST['content']
$response = array("success" => true, "message" => $content);
echo json_encode($response);
?>
我收到此错误:
FileUploader.js:20 POST http://localhost:8888/phpBackend/demo.php 500 (Internal Server Error)
UserForm._this.getPHP @ FileUploader.js:20
UserForm._this.onSubmit @ FileUploader.js:44
callCallback @ react-dom.development.js:100
invokeGuardedCallbackDev @ react-dom.development.js:138
invokeGuardedCallback @ react-dom.development.js:187
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:201
executeDispatch @ react-dom.development.js:461
executeDispatchesInOrder @ react-dom.development.js:483
executeDispatchesAndRelease @ react-dom.development.js:581
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:592
forEachAccumulated @ react-dom.development.js:562
runEventsInBatch @ react-dom.development.js:723
runExtractedEventsInBatch @ react-dom.development.js:732
handleTopLevel @ react-dom.development.js:4476
batchedUpdates$1 @ react-dom.development.js:16659
batchedUpdates @ react-dom.development.js:2131
dispatchEvent @ react-dom.development.js:4555
interactiveUpdates$1 @ react-dom.development.js:16714
interactiveUpdates @ react-dom.development.js:2150
dispatchInteractiveEvent @ react-dom.development.js:4532
FileUploader.js:25 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at FileUploader.js:25
最初存在跨域问题(cors),但已通过我添加的.htaccess文件修复了该问题:
<IfModule mod_rewrite.c>
Header add Access-Control-Allow-Origin: "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Content-Type"
RewriteEngine on
RewriteBase /
</IfModule>
有人知道为什么这会引发错误吗?
答案 0 :(得分:1)
您在第 2 行的 php 脚本中有一个拼写错误。您在行尾缺少一个分号。
<?php
$content = $_POST['content']; // there you missed the semicolon
$response = array("success" => true, "message" => $content);
echo json_encode($response);?>