How can I download a file using the POST method along with some headers and data (of the type: "content-type: application/x-www-form-urlencoded") in React Native?
When I send a request to the URL, the following is returned in the Response Header:
content-disposition: attachment; filename="PAPR_Pginas_Web_2.pdf"
content-type: application/pdf
date: Sun, 07 Aug 2022 13:59:00 GMT
last-modified: Thu, 01 Jan 1970 00:00:00 GMT
server: Apache
strict-transport-security: max-age=86400
x-powered-by: JSF/1.2
x-xss-protection: 1; mode=block
I'm using this code:
const donwloadPDF = async (uri) => {
const downloadInstance = FileSystem.createDownloadResumable(uri, FileSystem.documentDirectory + "file.pdf");
const result = await downloadInstance.downloadAsync();
if (result.status === 200) {
Sharing.shareAsync(result.uri, { dialogTitle: "Share or Save" });
} else {
console.log("Failed to Download");
}
};
const getFile = async (payload) => {
try {
const response = await fetch(URL, {
method: "POST",
headers: headers2,
body: formBody(payload),
});
const content = await response.json();
donwloadPDF(content); // Some URI
} catch (error) {
console.error(error);
}
};
But is returned the error: JSON Parse error: Unrecognized token '%'
I'm actually trying to download a zip file from a Gitlab REST endpoint that is supposed to return the the repository for a given projectID.
I used axios to call the endpoint and tried to directly upload the response data to S3, but it seems to be returning a corrupt file as the zip that it returns says it cannot be opened.
I am doing the downloading of this file in a serverless function and attempting to return an S3 URL to the client.
Headers for the response
res.headers {
date: 'Wed, 19 Jan 2022 13:44:42 GMT',
'content-type': 'application/zip',
'transfer-encoding': 'chunked',
connection: 'close',
'cache-control': 'max-age=0, private, must-revalidate',
'content-disposition': 'attachment; filename="third-project-eac3ea41c782df4bee4fe07ecc3bf356f7f74f47-eac3ea41c782df4bee4fe07ecc3bf356f7f74f47.zip"',
'content-transfer-encoding': 'binary',
etag: 'W/"12ae32cb1ec02d01eda3581b127c1fee"',
vary: 'Origin',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-request-id': '01FSS9A6W1RM77TYMFM6G7HKZ8',
'x-runtime': '0.063985',
'strict-transport-security': 'max-age=31536000',
'referrer-policy': 'strict-origin-when-cross-origin',
'ratelimit-observed': '2',
'ratelimit-remaining': '1998',
'ratelimit-reset': '1642599941',
'ratelimit-resettime': 'Wed, 19 Jan 2022 13:45:41 GMT',
'ratelimit-limit': '2000',
'gitlab-lb': 'fe-17-lb-gprd',
'gitlab-sv': 'localhost',
'cf-cache-status': 'MISS',
'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
'report-to': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=r6XcPGaiU7JhlicrSC9iBZgXXCOMoBMXjU8kvxjZGb5UkUQBIjemmAOOX39m1ijVCnQROVhNNxc6B%2B4x%2FNf5ZG9cc8GLY%2BfMYUE29gJkHN624QKJRSX8HBrMqEQ%3D"}],"group":"cf-nel","max_age":604800}',
nel: '{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}',
server: 'cloudflare',
'cf-ray': '6d007fcb7a8a8e63-PDX'
}
This it the code I'm using
const requestURL = `https://gitlab.com/api/v4/projects/${repoID}/repository/archive.zip?sha=${commitSHA}`;
let url = await Axios({
method: "GET",
url: requestURL,
headers: {
Accept: "*/*",
Authorization: "Bearer " + authToken,
},
})
.then(async (res) => {
const Key = "path/to/file";
const params = {
Bucket: BUCKET_URL,
Key,
Body: res.data,
ContentType: "application/zip",
};
await s3.upload(params).promise();
const URL = await s3.getSignedUrl("getObject", {
Bucket: BUCKET_URL,
Key,
ResponseContentDisposition:'attachment; filename = test.zip"',
});
return URL ;
})
.catch((error) => {
console.log(error);
});
return url;
But when I try and access this URL on my browser from the frontend, It returns a file test.zip which is larger and corrupt.
This is a screenshot of the data that I received on postman,
if I click save response and name the file filename.zip it shows the actual contents of the file.
Any help would be appreciated!
This worked!
const requestURL = `https://gitlab.com/api/v4/projects/${repoID}/repository/archive.zip?sha=${commitSHA}`;
let url = await Axios.get(requestURL,{
headers: {
Accept: "*/*",
Authorization: "Bearer " + authToken,
},
responseType:'arraybuffer'
})
.then(async (res) => {
const bufferData = Buffer.from(res.data)
const Key = "path/to/file";
const params = {
Bucket: BUCKET_URL,
Key,
Body: bufferData,
ContentType: "buffer",
};
await s3.upload(params).promise();
const URL = await s3.getSignedUrl("getObject", {
Bucket: BUCKET_URL,
Key,
ResponseContentDisposition:'attachment; filename = test.zip"',
});
return URL ;
})
.catch((error) => {
console.log(error);
});
return url;
async create() {
const data = {
name: this.name
};
const headers = {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.token}`
};
axios
.post("URL", data, headers)
.then(res => {
console.log('SUCCESS');
})
.catch(err => console.log(err.response));
}
The token from the login component. The token is loaded correctly as the POST request returns success when tried in Postman but the axios call returns
{ message: 'Unauthenticated.' },
status: 401,
statusText: 'Unauthorized'
Any pointers would be appreciated to identify the direction or root of this error.
You're passing the headers to the axios incorrectly. Try this:
const headers = {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.token}`
};
axios.post(URL, data, { headers })
That's why your Authorization header is not included in your request and the server returns 401.
I am using vue.js with axios to post my data.
Here i am calling two api's one on response of another with same data.
First api responds with 200 but on connecting second it returns with connection close 500 Internal Server Error.
//Axios
const formData = new FormData()
formData.append('myFile', this.chart_image);
formData.append('signal_title', this.form.signal_title)
axios.post('../api/trades/add.php' , formData, )
.then(function(response){
axios.post('../bot.php',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error.response);
});
})
.catch(function (error) {
console.log(error.response);
});
On response I am getting like this in array.
chart_image:File(777835)
lastModified:1247549551674
lastModifiedDate:Tue Jul 14 2009 11:02:31 GMT+0530 (India Standard Time) {}
name:"Penguins.jpg"
size:777835
type:"image/jpeg"
$update = json_decode(file_get_contents('php://input'));
I am using to extract the data from $update.
How to extract $update->form->chart_image->name ???
Any help would be very much helpful.
Thanks.
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"