我只是想让 php 文件“echo $string = 'hello world';”在我的 ReactJS 应用程序的 html 页面上。
但我从浏览器(Google Chrome)收到此错误:
“未处理的拒绝(语法错误):JSON 中位置 0 处出现意外的标记 h”
表明这是导致问题的行:
.then((response) => response.json()
我的 JavaScript:
import React, { Component } from 'react'
import './App.css'
class App extends Component {
componentDidMount(){
fetch('http://localhost/finaldemo.php')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
})
}
render () {
return (
<div>
<p> HELLO </p>
</div>
);
}
}
export default App;
我的 PHP:
<?php header('Access-Control-Allow-Origin: http://localhost:3000');?>
<?php
echo $string = 'hello world';
?>
问题出在哪里?
提前致谢!
最佳答案
response.json() 期望 fetch 的响应采用 JSON 格式。然后它会自动将其放入 JSON.parse 中以将其转换为 javascript 对象。
你的“hello world”只是文本而不是 JSON。你可以使用response.text(),然后它会期待一个文本。
或者你可以让 PHP 发送一个实际的 JSON,如 '{"message":"hello world"}'
关于javascript - "Unhandled Rejection (SyntaxError): Unexpected token h in JSON at position 0"与response.json(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50302433/