0

Hi i am trying to replicate a ios app in react-native.I am trying to make a get request with a authentication token in header. But getting below error : Exception has occurred: SyntaxError SyntaxError: Unexpected token < in JSON at position 0 at parse ()

I have tried following code :

  let webPath = 'http://some.domain..svc/GetContactDetails?UserEmail=5555';

        let request = {
          method: 'GET',
          headers: { 
            'Content-Type': 'application/json', 
            //'Authorization': 'Bearer ' + myToken, // won't works same error
            //'Token': myToken, // won't works same error
            'Authorization':{'Token':myToken}
          },
          //credentials: 'include',
        }

        fetch(webPath, request)
        .then((response) => response.json())
        .then((responseJson) => {

          console.log(responseJson)

        })
        .catch((error) => {
          console.error(error);
        });

In ios i am doing this using below code:

    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    let token_key = UserDefaults.standard.value(forKey: "token_key") as! String
    request.setValue(token_key, forHTTPHeaderField: "Token")

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

Any help will really be apppreciated. Thanks in advance

Hitesh
  • 11
  • 1
  • 2
  • Have you seen [this post](https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0)? You're probably receiving HTML (or XML) back from the server. – Milore Jan 29 '19 at 08:16
  • 1
    Thanks Milore for your help.... – Hitesh Jan 29 '19 at 11:12

2 Answers2

1

First there was some issue with my URL, If you encounters any problem, please first go through your code a few times.

Second I was receiving my data object in _bodyText part of response. So need a JSON parser to parse my data into a json objects as JSON.parse(response._bodyText); So below code works for me.

let request = {
          method: "GET",
          headers: {
            'Content-Type': "application/json",
            'Token': mytoken
          }
        };

    fetch(webPath, request)
          .then(response => {
            return JSON.parse(response._bodyText);
          })
          .then(responseJson => {
            console.log(responseJson);
            const DataDict = responseJson; 
            console.log(DataDict);
            let Status = DataDict["Status"];
          })
          .catch(error => {
            console.error(error);
          });

Also with resopnse.json() i was getting below response :

Promise {
13:54:17:   "_40": 0,
13:54:17:   "_55": null,
13:54:17:   "_65": 0,
13:54:17:   "_72": null,
13:54:17: }
Hitesh
  • 11
  • 1
  • 2
0

The request you're sending has nothing to do with the response. Its working fine. The problem is that the response you're getting is not JSON probably so javascript is unable to parse it. You can test it with some dummy api like https://jsonplaceholder.typicode.com/users to see if you're getting a response and it being parsed correctly. see the following code..

function getMoviesFromApiAsync() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
}

This is the example code for fetching data from server on Official React Native docs. https://facebook.github.io/react-native/docs/network

Awais Saifi
  • 67
  • 1
  • 8