Use Axios instead of Fetch with Cache API - javascript

I am successfully using fetch to download an image file and store in a custom cache:
await fetch(url).then( async (response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
I would like to switch this to axios so I can display download progress and stop the download if needed. I am able to successfully download the file:
await axios({
method: 'get',
url: url,
responseType: 'blob'
}).then( async (response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
But it returns and error: Failed to execute 'put' on 'Cache': parameter 2 is not of type 'Response'.
Referencing this question I also tried to manually create the response:
var init = { status: 200 , statusText: 'OK', type: 'cors', url };
var myResponse = new Response(response, init);
return cache.put(url, myResponse);
But it seems to override the other information and doesn't store the blob data at all:
Is axios able to create the type of response that is needed for the Cache API?
Edited to add: I've also tried changing the responseType to stream which is what fetch seems to return, but that didn't work either.

Related

Fetch vs Axios review?

I'm currently learning how to use axios and fetch api. I'm trying to make a request using a fetch api like this:
let response = await fetch('https://online.yoco.com/v1/charges/', {
method: 'POST',
headers: {
'X-Auth-Secret-Key': process.env.SECRET_KEY,
},
body: {
token: paymentToken,
amountInCents: 2799,
currency: 'ZAR'
}
});
let responseData = await response.json()
And an axios post request like this:
axios.post(
'https://online.yoco.com/v1/charges/',
{
token: 'tok_test_DjaqoUgmzwYkwesr3euMxyUV4g',
amountInCents: 2799,
currency: 'ZAR',
},
{
headers: {
'X-Auth-Secret-Key': SECRET_KEY,
},
},
)
.then(res => {
//code
})
.catch(error => {
// handle errors
})
Is the request the same or not?
Cause the fetch returns an error
No, those aren't the same, in two ways:
If you look at MDN's documentation for fetch, you'll see that it says this about body:
body
Any body that you want to add to your request: this can be a Blob, an ArrayBuffer, a TypedArray, a DataView, a FormData, a URLSearchParams, string object or literal, or a ReadableStream object. This latest possibility is still experimental; check the compatibility information to verify you can use it. Note that a request using the GET or HEAD method cannot have a body.
Notice that a plain object is not on that list.
You're not checking for HTTP errors. This is unfortunately a footgun in the fetch API (I wrote about it here): It only rejects its promise on network errors, not HTTP errors like 404.
I'm going to assume that your API accepts JSON. If so, you need to include the Content-Type header and call JSON.stringify:
let response = await fetch("https://online.yoco.com/v1/charges/", {
method: "POST",
headers: {
"X-Auth-Secret-Key": process.env.SECRET_KEY,
"Content-Type": "application/json", // ***
},
body: JSON.stringify({ // ***
token: paymentToken,
amountInCents: 2799,
currency: "ZAR",
}), // ***
});
if (!response.ok) { // ***
throw new Error(`HTTP error ${response.status}`); // ***
} // ***
let responseData = await response.json();

axios GET request with form data in React JS

I want to implement the following cURL request (which is working) in react js using axios:
curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id="uidxxxx"" --form "sign_id="
I always get the same error: field sign_id not found, but technically I'm sending it, so I'm kind of desesperate.
var data = new FormData();
data.append('user_id', 'uidxxxx');
data.append('sign_id', '9');
const api = axios.create({
baseURL: BASE_URL_SERVER,
data: data,
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
},
timeout: 10000,
})
api.get('/sendText')
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
I've also tried adding '...getHeaders()' to the headers section but React says it is not a function; I've read in other posts that it has something to do with the browser
thanks in advance
ps: it is a pretty similar problem to this one, but none of the solutions worked for me
[UPDATE]
I ended up implementing it with POST, which is better for posting Form Data; no headers are needed, the browser automatically adds them:
var data = new FormData();
data.append('user_id', user_id);
data.append('sign_id', sign_id);
const api = axios.create({
baseURL: BASE_URL_SERVER,
timeout: TIMEOUT_SERVER,
})
api.post('/sendText', data)
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
You have a mistake, you try to send data via axios for POST and method is GET...
So that, You need to Change Method to be POST to can Post form data or you need to change it to url param or url path base on your api to be WORK as a GET...
Base on your curl, your case is you need a GET:
// Make a request for a user with a given ID
axios.get('/sendText?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
sendText: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
Also, you can save all config in instance and share it for all nested of write it again and again..
for example:
// Common Axios Instance Config
const axiosConfig = {
baseURL: process.env.REACT_APP_API_ENDPOINT,
};
// Create Default Axios Instace
const instance = axios.create(axiosConfig);
I think base on your example this will work, but not sure sine I'm not test it..:
var data = new FormData();
data.append('user_id', 'uidxxxx');
data.append('sign_id', '9');
const api = axios.create({
baseURL: 'https://193.146.38.4:56076',
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
},
timeout: 10000,
})
api.get('/sendText', {
user_id: 111,
sign_id: 2222
)
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
For more details view this url

Phonegap: Is there a way to get JSON data from an external url?

Actually am kinda disappointed as I tried many things and checked out many articles but non worked out for me.
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://***********.com/connect/api.php?action=2&token="+tokenV;
const myHeaders = new Headers();
const myRequest = new Request(urlF, {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default',
});
fetch(myRequest)
.then(response => response.json())
.then(data => console.log(data));
}
I have already whitlist the domain inside my config file, am using phonegap CL latest version. I'm trying to connect to an api which will out put json.encode data if token were right.
Error output:
(index):50 Fetch failed loading: GET https://*******.com/connect/api.php.............
Another way I tried using cordova fetch plugin still failed:
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://*********.com/api.php?action=2&token="+tokenV;
console.log("nowww1");
cordovaFetch(urlF, {
method : 'GET',
headers: {
'User-Agent': 'CordovaFetch 1.0.0'
},
})
.then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
Error out put:
Error: exec proxy not found for :: FetchPlugin :: fetch (index):118 parsing failed TypeError: Network request failed
I can change the out put as I want but show me away to get the data from an external server???
Thank you

javascript fetch() works with breakpoints, but fails with TypeError when run normally

I'm trying to fetch() text/plain data from a remote service. If I place a breakpoint in the promise "then" chain, the text data from the server is available. Without the breakpoint, I get a fetch() exception.
I am using a prototype design pattern (see below). When I place a breakpoint in the "then" chain as shown below, the data from the remote service is successfully retrieved. Without the breakpoint, the catch() is executed and the error is:
TypeError: Failed to fetch
I'm totally stumped and would appreciate any help!
Note, the server (a python app) sends back html, with
self.send_header("Access-Control-Allow-Origin", "*")
Also, if I use Ajax (FWIW, it works). I'd like to get it working with fetch() however.
function Fetch(Msg) {
// Msg contains some info on how to construct the JSON message to transmit -- not relevant here.
this.help = `
The Fetch object specifies communication basics using
the fetch(...) mechanism.
`;
// some misc object vars...
}
Fetch.prototype = {
constructor: Fetch,
postData: async function (url = '', data = {}) {
const response = await fetch(url, {
method: 'POST,
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'text/plain',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
// body data type must match "Content-Type" header
body: JSON.stringify(data)
});
return await response.text(); //
},
handleErrorsInResponse: function (response) {
var debug = new Debug("Fetch.handleErrorsInResponse");
debug.entering();
debug.leaving();
},
handleReponse: function (response) {
var debug = new Debug("Fetch.handleResponse");
debug.entering();
console.log(response);
debug.leaving();
},
handleErrorsInFetch: function (response) {
var debug = new Debug("Fetch.handleErrorsInFetch");
debug.entering();
console.log(response);
debug.leaving();
},
call: function (payload) {
this.postData(
'http://some.url/',
payload)
.then(this.handleErrorsInResponse) // If I place a breakpoint here it works!
.then(this.handleReponse)
.catch(this.handleErrorsInFetch);
},
}
// Ultimately called by something like
comms = new Fetch();
someData = {"key": someJSON};
comms.call(someData);
Remove the wait on the response.
Replace
return await response.text();
by
return response.text();

React Native network error in POST request when adding a body

it's me again.
I'm learning react native, for now im trying to upload a file, the api is already tested using postman and it does work so I wrote this code:
import * as DocumentPicker from 'expo-document-picker';
async login () {
let response = await DocumentPicker.getDocumentAsync({type: '*/*'})
const data = new FormData();
data.append('file', response)
// Fetch attempt ----------------------------------------
fetch("http://192.168.0.3:8000/api/file", {
method: "POST",
headers:{
"Content-Type": "application/x-www-form-urlencoded",
},
body: data
})
.then(response => response.json())
.then(response => {
console.log("upload succes", response);
})
.catch(error => {
console.log("upload error", error, JSON.stringify(error));
});
// Axios attempt ----------------------------------------
axios.post('http://192.168.0.3:8000/api/file', data, { headers:{ "Content-Type": "application/x-www-form-urlencoded"} } )
.then(res => {
console.log("goddaamittt wooork", res)
})
.catch(error => {
console.log("error", error, JSON.stringify(error))
});
}
When I remove the body and headers from that request it actually returns what the api should return when you try to POST to it without a 'file', some message "{'fileName': 'A file is required'}" but adding it to it I get a network error, the error I get when using fetch it:
upload error [TypeError: Network request failed] {"line":24646,"column":31,"sourceURL":"http://127.0.0.1:19001/node_modules/expo/AppEntry.bundle?platform=android&dev=true&minify=false&hot=false"}
when it reaches the axios attempt it says something like this:
[Unhandled promise rejection: TypeError: Network request failed]
I tried everything I knew, I need some help!
Idk if it is important but here is what DocumentPicker returns when I pick a file:
Object {
"name": "FB_IMG_1573232116651.jpg",
"size": 32482,
"type": "success",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fjsonplaceholder-bcb4c1c6-b37d-4634-99a5-3410d9b8654e/DocumentPicker/db8d78dd-2587-40e4-aed9-656c36df29f4.jpg",
}
This is the error I get when I remove the body from the axios request
error [Error: Request failed with status code 400] {"config":{"transformRequest":{},"transformResponse":{},"headers":{"Accept":"application/json, text/plain, /"},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"method":"post","url":"http://192.168.0.3:8000/api/file"},"response":{"data":{"message":"File is required"},"status":400,"headers":{"map":{"cache-control":"public, max-age=0","x-robots-tag":"noindex","x-debug-token-link":"http://192.168.0.3:8000/_profiler/54e68c","x-debug-token":"54e68c","link":"http://192.168.0.3:8000/api/docs.jsonld; rel=\"http://www.w3.org/ns/hydra/core#apiDocumentation\"","content-type":"application/json","x-powered-by":"PHP/7.2.4","connection":"close","date":"Fri, 08 Nov 2019 17:54:12 GMT","host":"192.168.0.3:8000"}},"config":{"transformRequest":{},"transformResponse":{},"headers":{"Accept":"application/json, text/plain, /"},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"method":"post","url":"http://192.168.0.3:8000/api/file"},"request":{"url":"http://192.168.0.3:8000/api/file","credentials":"omit","headers":{"map":{"accept":"application/json, text/plain, /"}},"method":"POST","mode":null,"referrer":null,"_bodyText":""}},"line":178773,"column":26,"sourceURL":"http://127.0.0.1:19001/node_modules/expo/AppEntry.bundle?platform=android&dev=true&minify=false&hot=false"}
It was such a dump solution, it took me hours to find this:
When I get the file from DocumentPicker I had to add the type of the file because DocumentPicker return an odd type called "success", when I changed it to 'image/jpeg' it worked :D its not a solution at all because I will need to find a way to know what type of file is each file a user chooses, anyways, this code works c:
let response = await DocumentPicker.getDocumentAsync({type: 'image/jpeg'})
response.type = 'image/jpeg' // <- lasdfkasdfaslfkfsdkdsaf
const data = new FormData();
data.append('file', response);
axios.post('http://192.168.0.3:8000/api/file', data , {headers: { 'Content-type': 'application/x-www-form-urlencoded' }} )
.then(res => {
console.log("gooosh", res.data)
})
.catch(error => {
console.log("error", error, JSON.stringify(error))
});
you should try to modify the content-type to
fetch("http://192.168.0.3:8000/api/file", {
method: "POST",
headers:{
'Content-Type': 'multipart/form-data',
},
body: data
})
and for the form-url-urlencoded, the fetch is not supported. you have to push it by yourself.you can see this answer.

Categories

Resources