Javascript &引用;未处理的拒绝(SyntaxError):JSON中位置0处的意外标记h;带有response.json()

Javascript &引用;未处理的拒绝(SyntaxError):JSON中位置0处的意外标记h;带有response.json(),javascript,php,html,json,reactjs,Javascript,Php,Html,Json,Reactjs,我只是希望php文件在我的ReactJS应用程序的html页面上显示为“echo$string='hello world';” 但是我从我的浏览器(Google Chrome)中得到这个错误: “未处理的拒绝(SyntaxError):JSON中位于位置0的意外标记h” 指示这是导致问题的行: .then((response) => response.json() 我的JavaScript: import React, { Component } from 'react' import

我只是希望php文件在我的ReactJS应用程序的html页面上显示为“echo$string='hello world';”

但是我从我的浏览器(Google Chrome)中得到这个错误:

“未处理的拒绝(SyntaxError):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;
import React,{Component}来自“React”
导入“./App.css”
类应用程序扩展组件{
componentDidMount(){
取('http://localhost/finaldemo.php')
.then((response)=>response.json())
.然后((responseJson)=>{
console.log(responseJson)
})
}
渲染(){
返回(
你好

); } } 导出默认应用程序;
我的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,比如“{”消息“:“hello world”}”

response.JSON()希望fetch的响应是JSON格式的。然后它会自动将其放入JSON.parse中,以将其转换为javascript对象

您的“hello world”只是文本,而不是JSON。您可以使用response.text(),然后它将需要一个文本


或者您可以让PHP发送一个实际的JSON,比如“{”消息“:“hello world”}

检查Chrome开发工具中的“网络”选项卡以查看服务器响应的内容,并检查它是否为
内容类型:application/JSON

检查Chrome开发工具中的“网络”选项卡以查看服务器响应的内容,并检查它是否为
内容类型:application/json

hello world
不是有效的json。检查您的响应标题。它是
内容类型:application/json
或其他内容。
hello world
不是有效的json。请检查您的响应标题。它是
内容类型:application/json
或其他类型。不,顺便说一句,PHP和JS是fetch。如何修复它?Content Type:application/json只是内容头,内容头只是关于返回数据类型的信息您必须返回json数据才能使用response.json(),就像echo$string=“{text:'hello world'}”;不,顺便说一句,PHP和JS是fetch。如何修复它?Content Type:application/json只是内容头,内容头只是关于返回数据类型的信息您必须返回json数据才能使用response.json(),就像echo$string=“{text:'hello world'}”;