3

This question is seems to be already answered but my scenario is different. I am getting Unexpected token o in JSON at position 1 everytime. Can anyone help me to fix this.Thanks

here is my code

function send()
{

    let detail = new FormData();
    detail.append("start",true);
    detail.append("user",'david');
   
postRequest("https://myjson-url/game.php?"
,detail, getData);

}

function getData(res)
{

    let data = JSON.parse(res);
    console.log(data);

}
//async function
  async function checkStatus(res) {
    if (!res.ok) {
      throw new Error(await res.text());
    }
    return res;
  }

//my post request

    function postRequest(url, info, func){
        fetch(url, {method: "POST", body: info})
        .then(checkStatus)
        .then(func)
        .catch(console.error);
    }
8
  • Put your console.log above your JSON.parse and make sure you are getting a valid JSON response. Commented Nov 12, 2020 at 20:59
  • How about fixing game.php so that it returns valid JSON. Commented Nov 12, 2020 at 21:01
  • @RyanWilson Thanks for your response. Yes I just did I am getting console message but the rest of the JSON.parse is not working.. Commented Nov 12, 2020 at 21:01
  • 1
    @user3718511 If it's returning valid JSON you wouldn't be getting an error. Commented Nov 12, 2020 at 21:03
  • and here we go again... Commented Nov 12, 2020 at 21:03

2 Answers 2

14

It could be that in getData(res) the res is already a parsed JSON object so this line is not necessary :

let data = JSON.parse(res);

Try change it to

let data = res;
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer. I just tried but its not working..I am only getting response message from Response {type: "cors", url: "myjson-url/game.php?", redirected: false, status: 200, ok: true, …}
@user3718511 what do you expect to be getting? Does the response or res variable have a res.body attribute?
Does the res.body attribute contain the data you want to get from the server?
yes it is. Thats why I am confused why its not working..
JSON.parse() only parses a string into a javascript object. But res is already a javascript object. So it gives an error when trying to parse it. Res is not a string.
|
2

add json() let data = res.json();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.