27

"JSON Parse error: Unrecognized token'<'" Error is showing while hitting the api. Code is attached below Note* : Response is in the JSON format.

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
   };

Please help. Thanks,

2
  • 11
    This is almost certainly a server error (e.g. you're getting the 404 or index.html page rather than a JSON response), not a client error. Make sure that you can actually POST to that url with the data you have. You can also use response.text() to see the response text. Commented Jun 13, 2018 at 13:32
  • Thanks It is working. :) Commented Jun 14, 2018 at 4:18

16 Answers 16

36

This Means you are getting Html response from the server probably a 404 or 500 error. Instead of response.json() use response.text() you will get the html in text.

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.text())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + responseData
  )
}).done();
       this.props.navigation.navigate("Home")
   };

Sign up to request clarification or add additional context in comments.

Comments

6

You can try by adding the headers to your fetch api, as it posts your record to your url.

var dataObj = {}
dataObj.uname = uname,
dataObj.password = password

fetch("http:/example.com", {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',  // It can be used to overcome cors errors
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(dataObj)
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
    this.props.navigation.navigate("Home")
};

Comments

2

Finally The below code worked. The problem was with Body parameters.

fetch("http:/example.com", {method: "POST",
  body: "uname=value1&password=value2" // <-- Post parameters        
})
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
};

1 Comment

I assume Your server is not taking JSON formatted body
2

I am pretty sure all these answers are correct. From what I have seen, if you have properly set the request header with:

headers:{
    'Accept': 'application/json',
    'Content-Type':'application/json'
}

The Accept header will tell the server what data type we are sending. Content-Type tells the client of what the response data type will be.

You most likely had to change the format of the body because the server may not be setup to handle application/json data types. In this case if you have access to your server you can add it to a config file or in .htaccess. If you still get the error, then there is an error in the server's json response.

If you haven't used POSTMAN for API testing, go and grab it because it has helped me lots with debugging API's.

Comments

1

I also encountered this problem before. I solved it by adding this as a parameter in fetch.

header: {
  'Content-Type': 'application/json'
}

If it doesn't work, it's more likely an internal server error in the web service. Cheers.

Comments

1

I found this issue the upload the images on amazon S3 and image size is large. I upload the image on lower resolution and it's working fine for me.

Comments

1

In my case, I was using Infinity Free WebHosting for my API design and tests and apparently they dont allow exposure of API endpoints if you are using their free account.

That error means you are getting HTML code sent back to you and you have to do a console.log(data_response) to see the actual error. It is much easier if you are using Axios

Error that i was getting:

<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("c353693e65094689705f1b8cec0deb51");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>

Solution:

Try another different Shared Hosting service provider.

Comments

1

I was facing same issue, after spending hours, I came to figure out that there was a SPACE in my URL. like below

let url = "https://qinvite.vizzwebsolutions.com/api/edit_category "

So I removed SPACE from end and it got working.

Comments

0

this is likely when you receive html tag format from the server not the json check out the server encoding the data into proper json format you can check response by response.text() if it works than you are receiving text format.

1 Comment

Use correct spelling, punctuation, and grammar to the best of your ability.
0

I fixed this problem my changing the multiline URLs in template literals to single-line URLs.

I had this problem on iOS, but not Android. The "same" code according to version control, and state according to testing procedures, led to this error on the iOS device emulator but not the Android device emulator.

Apple and Windows use different line endings, which is important considering template literals allow multiline strings.

// failed in iOS
fetch(`https://<API-NAME>/
?param1=${param1}
&param2=${param2}`);

// consistently works
fetch(`https://<API-NAME>/?param1=${param1}&param2=${param2}`);

2 Comments

I think i have exact same problem. Same url works perfectly fine on Android but not on Ios. Can you be more specific? how did you fix the issue? thanks
@hyuklee, I edited my answer to show the working and failed code.
0

in my case the API website is protected by username and password, it is called basic auth.

so when i logged in from browser to the website and posted the same fetch url, it gave me the json response i needed, but when i logged in from another browser where i'm not authenticated it returned the html not authorized page.

so the answer might be a combination of both, missing headers & need for adding password and username of website in the request.

if you don't know how to add a basic auth:

  1. enter username and password here, it will be automatically generated, you can use another website to create it(https://www.blitter.se/utils/basic-authentication-header-generator/)

  2. add this to your requests (customize with your own basic auth)

    headers: { 'Authorization': 'Basic ZGV2VGVhbTpmc2xoZ2dpQHRh' }

VOILA.

Comments

0

fetch("http:/example.com", {method: "POST",
  body: "uname=value1&password=value2" // <-- Post parameters        
})
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
};

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1

Non of the Above mentioned answers worked for me.Infact When I was fetching the api it was done correctly like

      fetch('https://reactnative.dev/movies.json')
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });

but the problem was that when I tried to add the one more string in fetch i got an error like this was the code

   const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json'+text)
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }

Actually I wanted to make a searchable component so I added the following chracters to remove the error so that it can combine a string to filter the data as it is searched.

?query=

in fetch statement like this

   const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json?query=')
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }

The complete code that will show the filtering effect on console as you will search for a value is given below

import { text } from '@fortawesome/fontawesome-svg-core';
import React, { Component, Fragment, useState, useEffect } from 'react';
import { FlatList,SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Button, Image, TextInput } from 'react-native';
import BRAND_DRUG_UNIQUE from '../BRAND_DRUG_UNIQUE.json';



const Search = () => {
    const [city, setCity] = useState("")
    const [cities, setCities] = useState([])
    const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json?query='+text)
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }
    useEffect(()=>{
        
        // console.log("filteredData==> ",city);
    })
    return (
        <View style={{
            position: "relative", zIndex: 1000, borderWidth: 1, borderColor: "grey", shadowColor: "#000", marginBottom: 10,
            shadowOffset: {
                width: 0,
                height: 12,
            },
            shadowOpacity: 0.58,
            shadowRadius: 16.00,

            elevation: 24,
        }}>
            <View>
                <Text>
                    It is the search component
                </Text>
                <TextInput
                    placeholder="Search here if you want"
                    style={{ color: "#00aaff" }}
                    value={city}
                    onChangeText={(text) => fetchCities(text)}
                />
            </View>
        </View>
    );
}
export default Search;

Hope it helped.Thanks.

Comments

-1

I guess some url misspell may cause that error.

I faced that issue working with graphql requests. In my case the issue was in request url. There was https://my.domain//graphql with double /

And another case I came across was server responded with 502 error and that caused the error.

Comments

-1

I think you can't get response through response.json(). Because there is something like '<' in your response that cannot be converted to json. Try with response.text()

1 Comment

@ispirett already answer this
-1

In my case I was giving extra forward slash in the end point like I have a base URL https://forexample-api.herokuapp.com/ and in the components my fetch URL was ${link.baseUrl}/api/auth/login i.e. https://forexample-api.herokuapp.com//api/auth/login

Notice that there were 2 forward slashes before api/auth... Removing this extra forward slash solved my problem.

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.