最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern in ReactJS Website - Stack

programmeradmin0浏览0评论

I'm building a website using ReactJS that uses JSON present locally on my puter to fetch the information to be filled out. Here is the index.js file: -

import React from 'react';
import data from 'notes.json';

class BlogList extends React.Component {
    constructor(props){
        super(props);

        this.state={
            items:[],
            loaded: false
    };

}

/* useEffect()=>{
return function(){

}
},[deep])
*/      //Similar to ComponentDidUnMount();

ponentDidMount(){
    fetch(data)
    .then(response => response.json())
    .then(json => {
        this.setState({
            items: json,
            loaded: true,
        })
    })
    
 }

    render() {
        const {items, loaded} = this.state;

       if(!loaded){
            return <h3>Loading........</h3>
        }
        return (
            <div className="content-container" >
            {   
                items.map((item)=>(
                    <div key={item.id}>

                        <p>
                            {item.postId}
                        </p>
                        <p>
                            {item.id}
                        </p>
                        <p>
                            {item.name}
                        </p>
                        <p>
                            {item.email}
                        </p>
                        <p>
                            {item.body}
                        </p>
                        <hr/>
                    </div>
                ))

            }
        </div>
        );
    }
}

export default BlogList;

And the JSON file is here: -

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
  },
  {
    "postId": 1,
    "id": 3,
    "name": "odio adipisci rerum aut animi",
    "email": "[email protected]",
    "body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
  },
  {
    "postId": 1,
    "id": 4,
    "name": "alias odio sit",
    "email": "[email protected]",
    "body": "non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati"
  }
]

It is constantly giving me this error in the console: - Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.

I'm building a website using ReactJS that uses JSON present locally on my puter to fetch the information to be filled out. Here is the index.js file: -

import React from 'react';
import data from 'notes.json';

class BlogList extends React.Component {
    constructor(props){
        super(props);

        this.state={
            items:[],
            loaded: false
    };

}

/* useEffect()=>{
return function(){

}
},[deep])
*/      //Similar to ComponentDidUnMount();

ponentDidMount(){
    fetch(data)
    .then(response => response.json())
    .then(json => {
        this.setState({
            items: json,
            loaded: true,
        })
    })
    
 }

    render() {
        const {items, loaded} = this.state;

       if(!loaded){
            return <h3>Loading........</h3>
        }
        return (
            <div className="content-container" >
            {   
                items.map((item)=>(
                    <div key={item.id}>

                        <p>
                            {item.postId}
                        </p>
                        <p>
                            {item.id}
                        </p>
                        <p>
                            {item.name}
                        </p>
                        <p>
                            {item.email}
                        </p>
                        <p>
                            {item.body}
                        </p>
                        <hr/>
                    </div>
                ))

            }
        </div>
        );
    }
}

export default BlogList;

And the JSON file is here: -

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
  },
  {
    "postId": 1,
    "id": 3,
    "name": "odio adipisci rerum aut animi",
    "email": "[email protected]",
    "body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
  },
  {
    "postId": 1,
    "id": 4,
    "name": "alias odio sit",
    "email": "[email protected]",
    "body": "non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati"
  }
]

It is constantly giving me this error in the console: - Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.

Share Improve this question asked Feb 28, 2022 at 12:34 PRUBHTEJ SINGHPRUBHTEJ SINGH 431 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You may get this error if the server's response is text but you attempt to parse it as JSON using res.json().

fetch(serverUrl, {method: 'GET'})
.then((res) => res.json())
res.text() 

is appropriate if the server returns text.

In this situation Safari once gave me the OP's error, but Chrome was more specific: "unexpected token W in json at position 0" -- res.json() expects the first character of the string to be { or [ since that is how JSON begins.

Or, as Safari would say, "the string did not match the expected pattern."

For those people getting this error from reading a json file from the local or public folder make sure the file path is preceded correctly. If there is no initial "/" in the file name it's looking at current directory and it may not find the json file. So, instead of:

fetch("data.json")

try:

fetch("/data.json")

Since you are using ReactJs and your json file is local, just move the json file to public folder of your ReactJs app and it will fix it with proper referencing

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论