The api call returns excel data as a readable stream. It was not possible to make a JSON from the response. How can I read out the data from the api call correctly?
return fetch(my_url, {
method: "GET",
headers: headers,
}).then(response => response);
response.json() // Cou not read data, endend up in catch block
response.body
ReadableStream {locked: false}
locked: false
response header
{
"access-control-allow-origin": "*",
"cache-control": "no-cache",
"connection": "close",
"content-disposition": "attachment; filename=tabelle.xlsx",
"content-length": "6085",
"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"date": "",
"server": ""
}
Related
I´m refering to this post: Fetch: POST JSON data
I´ve copied the code which is linked down below.
My question is, is it possible to save for example "Content-Length" which i get as a response in the JSON-file as a variable with which i can continue to work?
Looking forward!
Thanks already!
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.text())
.then(res => console.log(res));
And my result is:
{
"args": {},
"data": "{\"a\":7,\"str\":\"Some string: &=&\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "br, gzip, deflate",
"Accept-Language": "*",
"Content-Length": "32",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Sec-Fetch-Mode": "cors",
"User-Agent": "undici",
"X-Amzn-Trace-Id": "Root=1-6388fb1d-3f7791960bdce04f36356182"
},
"json": {
"a": 7,
"str": "Some string: &=&"
},
"origin": "79.208.157.109",
"url": "https://httpbin.org/post"
}
Of course you can - just access it and store it in a variable:
const example = async() => {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
const response = await res.json()
const contentLength = response.headers['Content-Length'];
displayContentLength(contentLength);
}
function displayContentLength(length) {
console.log('The content length is: ' + length);
}
example();
I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results
and the body request looks :
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
})
.then((response) => {
if (response.status !== 200) {
return res.send(respone("500", response.data.result.data))
} else {
return res.send(respone("200", response.data.result.data))
}
})
.catch((error) => {
console.log(error);
return res.send(error)
})
the error show
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Content-Transfer-Encoding": "application/json",
"HTTP_API_KEY": "xxxx",
"User-Agent": "axios/0.27.2",
"Content-Length": 2
},
"method": "post",
"url": "xxxxx",
"data": "{}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
It seems you nested your headers inside another "headers" property.
Basically you're doing this
headers: {
headers: {
'Content-Transfer-Encoding': ...
}
}
As Zai showed in her answer you problem is your header variable:
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
is nested, when you do this:
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
what you are really doing is:
axios({
method: 'POST',
url: URL,
headers: headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
},
data : {
}
So your header: instead of being Content-transfer etc... is just 'headers'
try this:
const header = {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
also, i recommend you to do a console.log with your api call in order to find this problems faster and compare with postman, really helpful in develop phase (just use it in local, never push that log to production)
I'm doing a post request using axios in node.js.
The response is gzip data (behind, it's a huge json)
My goal is to read the json file behind the res (gzip).
Currently, my request is:
await axios({
method: "post",
url: process.env.API_URL + "/collection",
headers: {
"Content-Type": "application/json",
"Accept-Encoding": "gzip, deflate, br",
},
data: {
project: req.body.project,
platform: req.body.platform,
},
decompress: true,
}).then(async (response) => {
console.log(response.data);
});
But I receive data like:
�1�����Q��:GR}��"-��}$K�ևҹ\��°<ܖqw�Vmp�������Y!�����܋a�F�]� ���K%}0�rЈ^�<��/�>
��Q���C7��R>�]§.,j�rg�6�MUVH��_Xq�����}|��a����$����K��cˠ��[�vv�����o�6�v�?~�����h���'Kn.��e��ZUW�;���ŗ��Ӹ6j%��M������Էʫ�c1��A�����.�t8�����Ș,����_��C�����۬���?q$#�CFq...
Does someone have any suggestion?
Thanks !
In my case, I want to get the information of my accessToken (from Google provider), then I can send a GET request like this:
const googleOauth2Url = `https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${accessToken}`;
const { data } = await axios.get(googleOauth2Url, {
responseType: "arraybuffer",
decompress: true,
});
Then I receive the data that looks similar to yours. I investigate and find out that the data is compressed with gzip, then to use it we must decompress the data.
Now I use zlib.
zlib.gunzip(data, function (error, result) {
console.log(result.toString());
return result.toString();
});
And the final result is:
{
"issued_to": "some data,
"audience": "some data",
"user_id": "some id",
"scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
"expires_in": 2971,
"email": "sample#gmail.com",
"verified_email": true,
"access_type": "offline"
}
I use axios to send a POST HTTP request with some binary data like this:
axios.post(url, input, {headers: {'Content-Type': 'application/octet-stream'}})
When I got an Bad request error I printed out the request headers:
"headers" : {
"common": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/octet-stream"
},
"delete": {},
"get": {},
"head": {},
"post": {
"Content-Type": "application/octet-stream"
},
"put": {
"Content-Type": "application/x-www-form-urlencoded"
},
"patch": {
"Content-Type": "application/x-www-form-urlencoded"
}
}
I overrode the default headers (see below) and got Ok instead Bad request
axios.defaults.headers = {"Content-Type": "application/octet-stream"}
So the problem is fixed but I don't like overriding axios defaults. How would you suggest use axios.post to send the header correctly ?
I am having a problem sending an authorization header with dropzonejs
this.componentConfig = {
iconFiletypes: ['.jpg', '.png', '.gif'],
showFiletypeIcon: true,
postUrl: `${getBaseUrl()}/Controller/ImportImage`,
headers: {
'Authorization': 'Bearer'
},
};
<DropzoneComponent config={config} eventHandlers={eventHandlers} djsConfig={djsConfig}> </DropzoneComponent>
Based on the code the headers are define like:
var headers = {
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest"
};
So, defining like
headers: { "Authorization" : "Bearer AbCdEf123456" }
should work.