【问题标题】:"Unhandled Rejection (SyntaxError): Unexpected token h in JSON at position 0" with response.json()“未处理的拒绝(SyntaxError):JSON 中位置 0 的意外令牌 h”与 response.json()
【发布时间】:2018-10-22 11:13:36
【问题描述】:

我只是想让 php 文件“回显 $string = 'hello world';”在我的 ReactJS 应用程序的 html 页面上。

但我从浏览器(谷歌浏览器)收到此错误:

“未处理的拒绝(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;

我的 PHP:

<?php header('Access-Control-Allow-Origin: http://localhost:3000');?>
<?php
    echo $string = 'hello world';
?>

问题出在哪里?

提前致谢!

【问题讨论】:

  • hello world 不是有效的 json。
  • 检查您的响应标头。它是Content-Type:application/json 或其他。

标签: javascript php html json reactjs


【解决方案1】:

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

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

或者您可以让 PHP 发送一个实际的 JSON,例如 '{"message":"hello world"}'

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 不,顺便说一句 PHP 和 JS 是 fetch。我该如何解决?
    • Content-Type: application/json 只是内容标头,内容标头只是有关返回数据类型的信息,您必须返回一个 json 数据才能像 echo 一样使用 response.json() $string = "{text: '你好世界' }";
    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 2018-06-10
    • 2020-02-05
    • 2021-09-12
    相关资源
    最近更新 更多