I want download file on my ionic mobile app from amazon S3 but I have this issue Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin.
So I add "capacitor://localhost" on my CORS configuration on amazon S3 like this :
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"HEAD",
"GET",
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*",
"capacitor://localhost"
],
"ExposeHeaders": []
}
]
but I have always the same issue.
My download function :
async downloadResource(filename: string) {
try {
this.url = this.changeSpecialCharacter(this.urlFolder + filename);
let extention = this.getFileExtension(filename);
filename = this.getFileName(filename);
if (!filename.includes(extention)) {
filename = filename + '.' + extention;
}
if (!filename) filename = this.url.split('\\').pop().split('/').pop();
const response = await fetch(this.url, {
headers: new Headers({
'Origin': 'capacitor://localhost'
}),
mode: 'cors'
});
console.log(' response '+JSON.stringify(response));
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
console.log(' blobUrl '+JSON.stringify(response));
const result = await Filesystem.writeFile({
path: filename,
data: blobUrl,
directory: Directory.Documents,
encoding: Encoding.UTF8
});
console.log('File written', result);
} catch (e) {
console.error('error fetch '+e);
}
}
I test also with const response = await fetch("https://file-examples.com/storage/feeb72b10363daaeba4c0c9/2017/10/file_example_JPG_100kB.jpg", {mode: 'cors'}); I have the same issue. So the problem is from the device
Related
first way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages`
);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
Second way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages?access_token=${PAGE_ACCESS_TOKEN}`
);
/* url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});*/
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
the error I get :
error: {
message: 'Unknown path components: /messagesaccess_token=access_token
type: 'OAuthException',
code: 2500,
fbtrace_id: 'AbBJGVotjz3ijKKLzVE6_CM'
}
I'm receiving this error in both ways. both ways are escaping the '?' mark. I have no idea what is happening.. I'm using heroku for this. I tried deleting and redeploying the repository to confirm if the code is not updating. but still gives this error. :( .
I tried withot using URL and URLSearchParams and it worked!
below is my code:
static async callSendApi(requestBody) {
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(
`${API_URL}/${PAGE_ID}/messages`,
{
params: { access_token: `${PAGE_ACCESS_TOKEN}` },
},
{
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
In order to upload a file to Backblaze B2 directly from the browser, I need to send the X-Bz-Content-Sha1 header.
This header is the SHA1 of the added file.
This is from an example using raw JS and not DropzoneJS:
const file = uploadFileInput.files[0];
const reader = new FileReader();
reader.onload = function () {
const hash = CryptoJS.SHA1(CryptoJS.enc.Latin1.parse(reader.result));
/* snip */
xhr.setRequestHeader("X-Bz-Content-Sha1", hash);
};
reader.readAsBinaryString(file);
How can I generate a SHA1 of the file I add into DropzoneJS?
Here's my DropzoneJS code:
let myDropzone = new Dropzone("#dropzone", {
acceptedFiles: "image/jpeg,image/jpg",
maxFilesize: 100,
init: function () {
this.on("addedfile", function (file) {
fetch("/api/presign-upload-url", {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": csrfToken
},
method: "post",
credentials: "same-origin",
body: JSON.stringify({
key: file.name
})
})
.then(function (response) {
return response.json();
)
.then(function (json) {
console.log(file);
// I don't know how to generate the SHA1 here, `file`
// seems like the wrong object to work with?
let hash = "2";
myDropzone.options.headers = {
"Content-Type": file.type,
"Authorization": json.upload_url.authorizationToken,
"X-Bz-File-Name": file.name,
"X-Bz-Content-Sha1": hash,
};
myDropzone.options.url = json.upload_url.uploadUrl;
myDropzone.processFile(file);
});
});
}
});
I am trying to integrate a POST API call from a lambda function using Node.js 12.x.
I tried like below:
var posturl = "My post api path";
var jsonData = "{'password':'abcdef','domain':'www.mydomain.com','username':'abc.def'}";
var req = require('request');
const params = {
url: posturl,
headers: { 'jsonData': jsonData }
};
req.post(params, function(err, res, body) {
if(err){
console.log('------error------', err);
} else{
console.log('------success--------', body);
}
});
But when I am execute it using state machine, I am getting the below exception:
{
"errorType": "Error",
"errorMessage": "Cannot find module 'request'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Error: Cannot find module 'request'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)",
" at Function.Module._load (internal/modules/cjs/loader.js:667:27)",
" at Module.require (internal/modules/cjs/loader.js:887:19)",
" at require (internal/modules/cjs/helpers.js:74:18)",
" at Runtime.exports.handler (/var/task/index.js:8:14)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Here the posturl is my api path and jsondata is my key value pair data.
So How can I call a POST API from lambda function? How can I pass the entire jsondata key when call API? How can I parse the response after the service call?
Update: I have tried like below
All my details are passing with a key jsonData, where I can specify that? Without that key, it will not work.
exports.handler = (event, context, callback) => {
const http = require('http');
const data = JSON.stringify({
password: 'mypassword',
domain: 'www.mydomain.com',
username: 'myusername'
});
const options = {
hostname: 'http://abc.mydomain.com',
path: 'remaining path with ticket',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = http.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
};
source : How to Make an HTTP Post Request using Node.js
const https = require('https');
const data = JSON.stringify({
name: 'John Doe',
job: 'Content Writer'
});
const options = {
hostname: 'reqres.in',
path: '/api/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
I use rn-fetch-blob to upload an image. This works correctly in Android but does not work in iOS.
I use data parameter in response to create image link , and when I check response from iOS I found data is null in iOS response . I don't know why why data parameter is null when status is 200.
I tried all answers for same issues but they did not work for me!
code for Upload Image:
export const UploadImageService2 = async (
file: any,
): AxiosRequestConfig => {
console.log("UploadImageService2");
console.log("file: " + file);
let seps = `${file.path}`.split('/');
let filename = seps[seps.length - 1];
var fp = file.path + "";
const realPath = Platform.OS === 'ios' ? fp.replace('file://', '') : fp;
console.log("fb: " + fp);
console.log("filePath: " + realPath);
const data = [
{
name: 'Files',
filename,
type: file.mime,
// binary field data from a file path, use `wrap` method to wrap the path
data: RNFetchBlob.wrap(decodeURIComponent(realPath)),
// binary field data encoded in BASE64
// data: RNFetchBlob.base64.encode(file),
},
];
console.log("dataObj: " + JSON.stringify(data));
const response = await RNFetchBlob.fetch(
'POST',
`${BaseUrl}api/image`,
{
Authorization: 'Bearer ',
'Content-Type': 'multipart/form-data',
},
data,
);
return {
...(response ? response : {}),
...file,
};
};
That's function called by this:
_uploadSingleImage = async (file: any, sendCheckupForm) => {
console.log("_uploadSingleImage");
console.log("_file: " + JSON.stringify(file));
let response = await UploadImageService2(file);
// let response = await UploadImageService(file);
console.log('resp=>>>', response)
if (get(response, ['respInfo', 'status']) === 200) {
console.log("okkk");
const responseData = get(response, ['data'], file.name);
console.log("responseData: " + JSON.stringify(responseData));
const fileUrl = responseData.replace(/^"(.+(?="$))"$/, '$1');
// const fileUrl = 'myTestImage';
const attachedFiles = this.state.attachedFiles.map(i => i.path === response.path ? { ...i, status: 'success', FileName: fileUrl } : i);
console.log("attachedFiles: " + JSON.stringify(attachedFiles));
this.setState({ attachedFiles });
console.log('fileUrl', fileUrl)
this.setState({ receptionImage: fileUrl });
if (sendCheckupForm) {
// this.setState({showCheckupForm: false});
this.props.sendCheckupForms(
this.props.token,
this.props.orderDetails.Id,
{
fileList: [fileUrl],
},
);
this.props.getOrder(this.props.token, this.props.orderId);
}
} else {
console.log("Erorrr");
const attachedFiles = this.state.attachedFiles.map(i => i.path === response.path ? { ...i, status: 'error' } : i);
this.setState({ attachedFiles });
}
};
This is example Json response for rn-fetch-blob in iOS:
{ taskId: 'jgd8phv6w98zryggebvvkg',
type: 'utf8',
respInfo:
{ redirects: [ 'https://cp.azmayeshonline.com/api/image' ],
status: 200,
timeout: false,
taskId: 'jgd8phv6w98zryggebvvkg',
headers:
{ 'x-aspnet-version': '4.0.30319',
'Content-Length': '42',
'x-frame-options': 'AllowAll',
Date: 'Tue, 27 Oct 2020 19:34:43 GMT',
Expires: '-1',
Server: 'Microsoft-IIS/10.0',
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
'x-powered-by': 'ASP.NET',
Pragma: 'no-cache' },
respType: 'json',
state: '2',
rnfbEncode: 'utf8' },
info: [Function],
array: [Function],
blob: [Function],
text: [Function],
json: [Function],
base64: [Function],
flush: [Function],
session: [Function],
readStream: [Function],
readFile: [Function],
exif: null,
filename: 'IMG_0002.JPG',
path: '/Users/mesimac/Library/Developer/CoreSimulator/Devices/52589261-2055-4237-9DED-E4F8D71FD25B/data/Containers/Data/Application/5FC9EEDF-5710-4935-9380-F03114B291CF/tmp/react-native-image-crop-picker/7EF8432F-53A3-4A41-8068-159A5990623C.jpg',
height: 1024,
width: 1541,
data: null,
modificationDate: '1441224147',
localIdentifier: 'B84E8479-475C-4727-A4A4-B77AA9980897/L0/001',
size: 304799,
sourceURL: null,
mime: 'image/jpeg',
cropRect: null,
creationDate: '1255122560',
status: 'loading' }
Anyone suggestions for how I can handle this?
Try using:
data:RNFetchBlob.wrap(realPath)
instead of:
data:RNFetchBlob.wrap(decodeURIComponent(realPath))
The rest of your code looks fine. Anyway, you are replacing the fp.replace('file://', ''), which is needed for iOS.
This is how I did it in my code:
data:RNFetchBlob.wrap(this.state.file.uri.replace("file://", ""))
I'm using react-native-camera(^0.6.0) in my app, I have to upload the recorded video to server as multipart data. In android they are posting like this,
{
_parts: [
[
'file',
{
name: 'VID_20181130_150959.mp4',
uri: 'file:///storage/emulated/0/DCIM/VID_20181130_150959.mp4',
type: 'video/mp4'
}
]
]
}
but in iOS the file path is returning as assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0&ext=mov but if I post the assets path it's not uploading.
{
_parts: [
[
'file',
{
name: '41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
uri: 'assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
type: 'video/mov'
}
]
]
}
Can anyone help me out with this????
I'm using iPhone 6 for debugging the code,
var url = DomainAPI.lashHostname + '/attachments?token=' + value + '&class=Quick';
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify(formData)
}).then((response) => response.json())
.then((responseData) => {
console.log('responseData------->************$$$$$$$$$$$' + JSON.stringify(responseData));
if (responseData.error.code == 0) {
this.sendFiletoServer(responseData.id, value);
} else {
this.setState({ loading: false });
Actions.pop();
}
}).catch((err) => {
console.log('responseData-------> err ************$$$$$$$$$$$' + JSON.stringify(err));
this.setState({ loading: false });
Actions.pop();
});
See This code worked for me hope it helps
let formData = new FormData();
formData.append("videoFile", {
name: name.mp4,
uri: video.uri,
type: 'video/mp4'
});
formData.append("id", "1234567");
try {
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
});
return await response.json();
}
catch (error) {
console.log('error : ' + error);
return error;