Why my headers are being lowercased? - aurelia

let headers = new Headers();
headers.append('Accept', '*/*');
headers.append('Content-Type', 'multipart/form-data');
let payload = await this.http.fetch(path, {
method: 'post',
body: item,
headers: headers
}).then(response => response.json())
.catch(err => err);
I am creating this piece of code to post a file to the server. When making the request this converts the header from Content-Type to content-type, Accept to accept, and this is causing me problems, I am using Aurelia + TypeScript.
Any ideas to avoid this behavior?

Related

Downloading blob (zip) from one endpoint and uploading to different endpoint

I'm trying to download a zip from one endpoint and upload to another from a FE VueJS app, but it ends up corrupted on upload. I can do it with fileSaver but was hoping to skip the intermediate step of dropping it onto a HDD. If I download and POST it with Postman it works fine, so I suspect there's an issue with the responseType or blob type etc, but there's a lot of combinations & permutations. cURL works fine as well, but obviously not applicable here.
This is the code so far, the fetch code/config is from Postman, but how the uploaded file is stored/represented in Postman is opaque. The zipEndpointUp is an endpoint that consumes the file but it returns 'invalid archive'. localhost:8080 is proxied to the actual server to avoid CORs issues.
axios.get("http://localhost:8080/zipDirDown/download.zip, {
headers: {
Authorization: "Basic xxx",
mode: "no-cors",
responseType: 'arraybuffer',
}
}).then(res => {
const blob = new Blob([res.data], {type: "octet/stream"});
let myHeaders = new Headers();
myHeaders.append("Authorization", "Basic xxx");
let formData = new FormData();
formData.append("file", blob, "newZipFile.zip");
formData.append("name", "newZipFile Name");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formData,
redirect: 'follow'
};
fetch("http://localhost:8080/zipEndpointUp", requestOptions)
.then(response =>
response.text())
.then(result =>
console.log(result))
.catch(error =>
console.log('error', error));
})
So it turns out I needed to await the res promise (and change the Blob type):
fetch("http://localhost:8080/zipDirDown/download.zip, {
headers: {
Authorization: "Basic xxx",
responseType: 'arraybuffer',
}
}).then(res => {
const asyncBlob = await res.blob();
const blob = new Blob([asyncBlob], {type: "application/zip"});
})

How to set the request headers that i send in postman, but in the navigator?

In postman is a section where you can put or set a header. But how do i set it but in the navigator, that lasts over time through requests to different routes?
I´ve already tried setting a header, from the backend with differents methods like, and none of both worked:
res.header('x-token', jwt)
Or like
res.set('x-token', jwt)
And from the frontend i already tried with this methods and it didn´t work either:
const data = {id_token};
//let myHeaders = new Headers();
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(resp => resp.json())
.then(({jwt}) => {
if (jwt) {
localStorage.setItem('x-token', jwt);
//None of both worked
//myHeaders.append('x-token', jwt);
//myHeaders.set('x-token', jwt);
}
})
.catch(error => console.error('Error:', error))
This is the header that i wanna send to the different routes:
https://i.stack.imgur.com/ueoxu.png
You can set the x-token header from your screen shot like this:
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json',
'x-token': 'eyJhbGciOiJIUzl.....'
}
}).then(...).catch(...)

React Native Fetch Request Network Error

I've seen previous answers on similar queries to this, but i'm still seeing a network error.
Here is my code:
let base64 = require('base-64');
let url = 'https://super_secret.com';
let username = '**supersecret**';
let password = '**supersecret**';
let headers = new Headers();
//headers.append('Content-Type', 'text/json');
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
let APIcall = function checkOrgCode() {
return fetch(url, {
method: 'GET',
headers: headers
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
If i comment out headers.headers and test a simple un-authorized API like https://jsonplaceholder.typicode.com/posts/1 then everything works fine, so clearly authoriation is failing.
When i test my API and headers in postman everything is fine though. I've also tried directly putting the base64 encoded string directly in the headers rather than using the encode function in my code.
Instead of using new Headers() to create the headers, try just a basic object to make life easy:
return fetch(url, {
method: '**PROPER METHOD HERE**',
headers: {
// 'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(username + ":" + password)}`
}
})
erm, so the issue was that the URL i am using isn't in place. I'd been using a hostname file hack which ofcourse works from postman on my PC, but not other mobile devices where i am testing.

React Native fetch API cannot disable caching

I am building android app using react native expo integrated with redux. The API is called using fetch method, but always the cached result is displayed. The server did not receive the request second time. I tried disabling cache with the following code.
export const mymails = (token) => {
return fetch(
API_URL+'?random_number='+ new Date().getTime(), {
method: 'GET',
headers: getHeaders(token)
})
.then(response => response.json());
};
getHeaders = (token) => {
return {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token='+token,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': 0
};
}
When I call the API through Postman client I see different result(not cached). I tried adding random number as parameter and setting cache control headers, but still returning cached result. Is there is anything else I could try.
Thanks
There must be a problem with how are you setting up the headers for fetching request.
Try with following,
You can follow the link for the same in the Official Fetch API
const mymails = (token) => {
var myHeaders = new Headers();
myHeaders.set('Accept', 'application/json');
myHeaders.set('Content-Type', 'application/json');
myHeaders.set('Authorization', 'Token token=' + String(token));
myHeaders.set('Cache-Control', 'no-cache');
myHeaders.set('Pragma', 'no-cache');
myHeaders.set('Expires', '0');
return fetch(
API_URL + '?random_number=' + new Date().getTime(), {
method: 'GET',
headers: myHeaders
})
.then(response => response.json());
};

react-native fetch - request body - Unexpected EOF

in my react-native application, I'm trying to make fetch request with body. But, I get error message of unexpected EOF. Actually, the request is made, I mean I can see through backend logs that request is sent, whereas, right after the request, it shows error message.
Here is my fetch method.
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.json())
.then((responseJson) => {
console.log("SEND_SMS RESULT: ",responseJson);
})
.done();
here is the error screen I get.
I would say that it fails on this line: response.json()
Are you sure that your response is a valid JSON?
Try testing the response with Postman or add .catch(e => console.log(e)) before done();
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.text())
.then((responseJson) => {
const resposeJson2 = responseJson.length ? JSON.parse(responseJson) : {};
console.log("SEND_SMS RESULT: ",responseJson2);
})
.done();
Your server is returning null instead of error and unfortunately response.json() cant operate on null response
you can research briefly on it the keywords are "Handling null response from api"