I am using fetch in React Native in order to make a call to my API, however, it only works 75% of the time.
When my request doesn't work I get this :
TypeError: Network request failed
or
SyntaxError: Unexpected token < in JSON at position 0
fetch('http://localhost/vision.php', {
method: 'POST',
headers: {
'Accept': 'application.json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
key: 'Mon paramètre'
})
})
.then((data) => data.json())
.then((dataJson) => {
console.log(dataJson.message);
})
.catch((error) => {
console.log(error);
});
}
Someone can explain that ?
When you get TypeError: Network request failed, it means that, well, the network request failed. It could mean the API / server you're trying to connect to is down / not listening for connections anymore.
Regarding SyntaxError: Unexpected token < in JSON at position 0, that's what you get when trying to parse non-JSON as JSON. Typically here it's likely your API / server failing to fulfill your request and, instead of JSON, serving you an HTML error page.
You might want to check if data.ok is true before trying to parse the JSON response (data.json()).
Related
I am using Axios library to retrieve Auth0 access tokens.
const { data, status, statusText } = await axios.post( https:auth0.url,
body,
{ headers: { "content-type": "application/x-www-form-urlencoded" } });
`
The issue i have is when i am using Axios 1.1.3 to retrieve access-tokens from Auth0 its giving me a proper response.
But when i update the library to 1.2.0 and higher everything breaks. I am getting a response for the same code as raw data
/#����W�{��bhu�E
:U�ȦG>SQ��6�y:90��w>B��� f�4:cA�P��V/����)��v%�_P�ɳ���ꑄ=lb���-F��zh�^X
��N�ˠ��G�
o����W(�Žx>�͔{�5*�������I������`�
���fA\��x~KS[
j��p�Ӌ<���u�qog�.)0G�FI/��R��OԽ�sm�ԝ{X�vV��s$i���2p`� �h�x_Ц��Z�u�9�X�d���B+P���l �m�h�Y��2���ԙ2
��Wx0K
� �Y2IX�d�����P�֎NЂu�qo���f".AJ��+���K枖0�
The stranger part is when i try to use the same code to get the result of an open source api.
const results = await axios.post("www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json",
{ headers: { "content-type": "application/x-www-form-urlencoded" } });
I am getting a correct response.
I believe i am only getting this response when i am receiving a token from Auth0. Atleast in my use case
The error i am receiving when i call Auth0 to get tokens is
cause: Error: unexpected end of file
at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) {
errno: -5,
code: 'Z_BUF_ERROR'
}
Is anyone else facing the same issue?
bench-vue Thank you for your sample code. I had to add 'Accept-Encoding' in the request header to receive the tokens. Thank you for your help
this is my very first time using Dialogflow, so probably my mistake is very stupid.
here is my problem:
1) I created a sample agent "small-talk'.
2) I enabled the Webhook in the fulfilment section. I setup the URL of the web server making the request and the auth (username, password) of the that web server.
3) I uploaded a simple webpage on that web server with an API request that looks like this one below (this is the sample json referenced in their guide):
axios({
method: 'POST',
url: 'https://api.dialogflow.com/v1/query?v=20150910',
headers: {
'Authorization': 'Bearer ad7829588896432caa8940a291b66f84',
'Content-Type': 'application/json',
},
body: {
"contexts": [
"shop"
],
"lang": "en",
"query": "I need apples",
"sessionId": "12345",
"timezone": "America/New_York"
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
I keep getting this error:
Cannot parse json. Please validate your json. Code: 400"
The only thing I can thing of, is that I noticed that Dialogflow is now working with the API V2 enabled by default in the agent settings and it seems there is no selection to V1 available anymore. But maybe this has nothing to do with my problem.
Thanks in advance!
Solved it!
In the json request, instead of
body: {...}
I replaced it with
data: {...}
Probably it was obvious, but I am an absolute newbie on these things!
By the way, Google has shutdown Dialogflow V1 starting from 12th July 2021 as per this URL - https://cloud.google.com/dialogflow/docs/release-notes#June_15_2021
In case you are getting http response code 400 (bad request), it means that it is time to migrate :-)
I'm developing React Native application which is connected to Web API written in ASP.NET Core 2.1. I'm trying to make GET request to my secured API's endpoint, but it doesn't work both with fetch and axios.
Noteworthy is fact, when I make request to unsecured (marked as AllowAnonymous) endpoint, everything works fine.
I'm passing following header 'Authorization' : 'Bearer ' + MY_TOKEN
When I tried to use axios, then it returned HTTP 401. When using fetch it returns HTTP 500.
const url = `${baseUrl}/api/cars/get`
fetch(url, {
headers: new Headers({
Authorization: "Bearer <MY_TOKEN_HERE>"
}), method: "GET"
})
I'm sure the token is valid because I am able to get data from API with Postman and with .NET Core console application client.
Is there any way to get the data from secured API's endpoint?
I solved the issue with just one line of code.
axios.defaults.headers.common['Authorization'] = `Bearer ${TOKEN}`
Then I am able to invoke the get request.
const url = `${baseUrl}/api/values`;
axios.get(url)
.then(data => {
console.log(data);
})
.catch(error => {
})
Hope it helps someone who will have such issue in the future.
I've created a small project with a node back-end and react front-end to fetch the data through REST calls. I used Axios library, but when I pass the headers with it I keep getting an error saying:
Failed to load resource: the server responded with a status of 401 (Unauthorized).
I found out two methods and both did not work. They are:
export const getUsersDetails=()=>{
console.log('calling');
return (dispatch) => {
return axios.get('http://localhost:3030/users',{headers: { "Authorization": localStorage.getItem('jwtToken') }}).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
and
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
But When I use postman I am getting the required data from the backend. Any particular reason why I keep getting this Unauthorized error?.
You need to concatenate 'Bearer ' before the token, like this:
axios.defaults.headers.common['Authorization'] =
'Bearer ' + localStorage.getItem('jwtToken');
I am trying to load Behance project data via their API. Whether its localhost or prod, I am getting the following error --
Fetch API cannot load XXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Not sure how to solve for this.
My code in the Portfolio component below --
getPortfolio = () => {
const USER_ID = `XXX`,
PROJECT_ID = `XXX`,
API_KEY = `XXX`;
const BEHANCE_URL = `https://api.behance.net/v2/users/${USER_ID}/projects?client_id=${API_KEY}`;
console.log(BEHANCE_URL);
fetch(BEHANCE_URL, {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
return response.json();
}).then((responseData) => {
return responseData;
}).catch((err) => {
return err;
});
}
UPDATE: Instead of fetch, using jQuery ajax works. --
$.ajax({
url: BEHANCE_URL,
type: "get",
data: {projects: {}},
dataType: "jsonp"
}).done((response) => {
this.setState({
portfolioData: response['projects']
});
}).fail((error) => {
console.log("Ajax request fails")
console.log(error);
});
This seems to have do less with React and more with Behance. What you are getting is a CORS error as you probably figured out. The short explanation is that CORS is a security measure put in on the browser so that websites cannot request other websites from the browser to appear to be the second website. It is a safety measure in place to protect from some phishing attacks.
CORS can be disabled by the server (in this case, Behance) but they decide not to, for legitimate reasons.
Behance would probably allow you to make the request you are trying to make from a server instead. Once you do that, you will need to get the information from your server to your React application, and you will be good to go!