How to convert a file-path URI to a readable https URL - javascript

Is there a way to convert a captured file path uri as such
file:///var/mobile/Containers/Data/Application/1E1E919E-6C21-4CC7-B9C2-5B4B3BC84B0F/Library/Caches/ExponentExperienceData/%2540chuks93%252Fihu-main/Camera/F3B8EBCC-BB09-4603-AF7E-FD3CA792C237.jpg to say a temporary https URL?
Im working with the Microsoft azure face API and I'm running into errors that suggest that only way to run the API is with network URLs like https.
Anyone know of a workaround solution for this?
export default {
processImage: (image) => {
// Replace the subscriptionKey string value with your valid subscription key.
var subscriptionKey = "********************";
var uriBase = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
// Display the image.
var sourceImageUrl = image;
console.log(typeof sourceImageUrl)
console.log("here", sourceImageUrl);
// Perform the REST API call.
return fetch(uriBase, {
method: 'POST',
headers: {
"Content-type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
body: JSON.stringify({ uri: sourceImageUrl })
})
.then((data) => data.json())
.then(function (data){
console.log("hello", data);
})
.catch(function (error) {
console.log(error);
});
}
}

Related

Why can't I send a form data from axios?

I am consuming an api that asks me to send a filter series within a formData, when doing the tests from Postman everything works without problem, I tried with other libraries and it also works without problem, but when trying to do it from axios the information does not return with the filters.
This is the code I am using:
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'get',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
You can send Form-data using get method, but the most servers, will reject the form data.
However it is not recommended anymore. The reason is, first because it is visible in the URL and browsers can cache them in it’s history backstacks, and second reason is because browsers have some limitations over the maximum number of characters in url.
If you are to send only few fields/input in the forms you can use it but if you have multiple inputs you should avoid it and use POST instead.
At the end it depends on your own usecase. Technically both GET and POST are fine to send data to server.
replace get with post
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'post',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});

How to avoid the field changing in Postman?

I'm trying to make HTTP requests to a Netsuite server and I'm using Postman to test them. Then I'm using the JavaScript code generated by Postman in VSCode and it works only the first time. If I want to make another test, I have to send it first from Postman and then copy-paste the code to VSCode again, because some fields of the 'Authorization' parameter change every time a request is sent. Is there a way to avoid this? Or should I do something different in VSCode? These are the parameters I'm using in VSCode:
'Authorization':'OAuth realm="",
oauth_consumer_key="",
oauth_token="",
oauth_signature_method="",
oauth_timestamp="",
oauth_nonce="",
oauth_version=""
oauth_signature=""',
'Cookie': ''
The ones that always change are oauth_timestamp, oauth_nonce, oauth_signature. Here's the complete code:
var axios = require('axios');
var config = {
method: 'get',
url: 'https://url',
headers: {
'Authorization':'OAuth realm="",
oauth_consumer_key="",
oauth_token="",
oauth_signature_method="",
oauth_timestamp="",
oauth_nonce="",
oauth_version=""
oauth_signature=""',
'Cookie': ''
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
try with async function:
something like this:
async function(){
try {
const userToken = await AsyncStorage.getItem('userToken');
let {data} = await axios.get("http://104.248.125.152:1337/api/tasks-category/format",{
headers:{
Authorization: `Bearer ${userToken}`
}
})
if (data) {
let info = data.data
setTasks(info)
}
} catch (error) {
console.log(error)
}
}

Uploading Image to AWS presigned post URL using axios

I am trying to upload an image to an S3 bucket using a presigned URL generated using boto3 on Python. I have been using the example python code that was provided in the documentation and was successful (the image got correctly uploaded with the correct Content-Type). However, when trying to do this in Javascript for the purposes of our frontend application, I am really struggling to get it to work.
Here's the example dictionary returned by the backend:
{
"fields": {
"AWSAccessKeyId": "AKIAYS3VM3EBIFL7FKE5",
"key": "posts/623255a762fd9bdfbd13f91a",
"policy": "<very long string>",
"signature": "Qvc/sGBHk0uzirzIfR1YmE2kFlo="
},
"url": "https://hotspot-storage.s3.amazonaws.com/"
}
Here is the functioning Python code:
response = <json response object>
object_name = 'playground/example_profile_group.png'
response['fields']['Content-Type'] = "image/png"
# Demonstrate how another Python program can use the presigned URL to upload a file
with open(object_name, 'rb') as f:
files = {'file': (object_name, f)}
http_response = requests.post(response['url'], data=response['fields'], files=files)
# If successful, returns HTTP status code 204
print(http_response)
print(http_response.text)
Here is the non-functioning Javascript code:
const data = response.data;
let payload = data.fields;
payload['Content-Type'] = 'image/jpeg';
const file = {
uri: previewPath,
name: previewPath,
type: 'image/jpeg',
};
payload.file = file;
const url = data.url;
console.log(payload, "MY PAYLOAD")
axios({
method: 'post',
headers: {'Content-Type': 'multipart/form-data'},
url: url,
data: payload,
})
.then(function (response) {
console.log(response.data, 'uploaded');
const data = response.data;
})
.catch(function (error) {
console.log(
'error uploading image',
error.response.data,
);
});
})
.catch(function (error) {
console.log(
'error getting media link',
error.response.data,
);
});
This is the error that keeps getting returned:
error uploading image <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>MalformedPOSTRequest</Code><Message>The body of your POST request is not well-formed multipart/form-data.</Message><RequestId>Q0ES6P4QP75YVVED</RequestId><HostId>eowLxSJQD1xP1EfHPnzGSJzXVGpPjurIMhkdwAD22JMvi9zRoFGg6Bq+mnUt/Lu7DNPY80iBDMc=</HostId></Error>
I have been stuck on this for an absurd amount of time, and cannot tell what I am doing wrong. Any help would be very much appreciated.
In order to send a multipart/form-data request body, you'll need to use a FormData instance instead of a JavaScript object.
For example
const { url, fields } = response.data;
const payload = new FormData();
payload.append("file", file); // this is the file blob, eg from <input type="file">
payload.append("Content-Type", "image/jpeg");
// add all the other fields
Object.entries(fields).forEach(([ key, val ]) => {
payload.append(key, val);
});
// No need to manually set content-type header, your browser knows what to do
const { data: result } = await axios.post(url, payload);
console.log("uploaded", result);

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

Categories

Resources