Reputation: 3859
"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,
Upvotes: 27
Views: 146928
Reputation: 1
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")
};
Upvotes: 0
Reputation: 188
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.
Upvotes: -1
Reputation: 67
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()
Upvotes: -1
Reputation: 1261
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.
Upvotes: -1
Reputation: 552
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.
Upvotes: 1
Reputation: 288
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.
Upvotes: -1
Reputation: 2636
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:
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/)
add this to your requests (customize with your own basic auth)
headers: { 'Authorization': 'Basic ZGV2VGVhbTpmc2xoZ2dpQHRh' }
VOILA.
Upvotes: 0
Reputation: 1304
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.
Upvotes: 1
Reputation: 1518
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}
¶m2=${param2}`);
// consistently works
fetch(`https://<API-NAME>/?param1=${param1}¶m2=${param2}`);
Upvotes: 0
Reputation: 655
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.
Upvotes: 2
Reputation: 1
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.
Upvotes: 0
Reputation: 666
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")
};
Upvotes: 36
Reputation: 2485
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.
Upvotes: 1
Reputation: 290
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.
Upvotes: 1
Reputation: 3859
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")
};
Upvotes: 2
Reputation: 1590
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")
};
Upvotes: 6