How to send Base64 to API - javascript

I am ultimately trying to send a fax with the Vitelity API. I have an API on EC2 that I am calling from my React Native app:
// Encoding to Base64
const encodeB64 = () => {
RNFS.readFile(croppedImage, 'base64').then(res => {
sendB64(res);
});
};
const sendB64 = b64 => {
let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let raw = JSON.stringify({
data1: b64, // 'jdl3439fdjsle/jjug'
login: {login},
pass: {pass},
faxnum: {destinationNum},
faxsrc: {sourceNum},
recname: 'Test',
file1: 'testfax.jpg',
});
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(API_URL, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
};
However, this returns an error cannot POST. If, instead of b64, I change data1's value to something like jdl3439fdjsle/jjug, everything is great.
Do I need to do something special to b64 before I can send it?
My Base64 looks like: /9j/4AA{1.2m more chars}uB//9k=. I've pasted it into a converter and it produces the correct image.

I geuss you have to use a Multipart Form with multipart/form-data as content-type headers if you want to send images. See also this question.

Related

How to correctly consume a rest service created with Genexus?

I have been trying to consume a simple web service crated with GeneXus, it should receive a "nPais" variable (integer) and respond an object with the text property based on the given number. It just doesn't work. I have confirm that the service work by testing it with soapUI (adding the WSDL), but when trying to consume it with postman it responds the correct structure, but with the text property empty.
This is my source tab from the WS.
&sdtServicio = New()
&Servicio.SetEmpty()
Do Case
Case &nPais = 1
&sdtServicio.Texto = "Hola México"
Case &nPais = 2
&sdtServicio.Texto = "Hola Argentina"
Otherwise
&sdtServicio.Texto = "HOLA MUNDO"
Endcase
This is on rules tab
Parm(in:&nPais, out:&sdtServicio);
And here is how I have been trying to consume the service on JS.
function getGreeting(value) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "GX_CLIENT_ID=54f383cc-0719-444d-a252-c8799c1202a0");
var raw = JSON.stringify({
"nPais": 1
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost:8080/PotentorDesaPotDesa/rest/WSHolaMundo", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
This is the response I get.
{"sdtServicio":{"Texto":""}}
The trick was only to change the protocol from SOAP to internal on the properties of my object.

How to unmarshal array in POST request

I am trying to make a POST request to an API server and I am sending an array of JSON, the problem is that I get this error:
cannot unmarshal array into Go value of type models.UserRequest
I tried to unmarshal it using a factory and then initializing the objects, but I still get this error, how can I fix this error and make my request? Here is my code:
import fetch from 'node-fetch';
import xlsx from 'xlsx';
const baseUrl = "";
const apiToken = "";
const accountId = "";
const wb = xlsx.readFile('users.xlsx');
const ws = wb.Sheets['users'];
const data = xlsx.utils.sheet_to_json(ws);
// console.log(data)
const options = {
method: "POST",
headers: {
Authorization: `Bearer ${apiToken}`,
"gtmhub-accountid": accountId,
"Content-type": "application/json; charset=UTF-8",
Accept: "application/json, text/plain, */*",
},
body: JSON.stringify(
data
),
};
const createUser = (url, settings) => {
return fetch(`${url}/users`, settings)
.then((response) => response.text())
.then((data) => console.log(data))
.catch((error) => {
console.log(error.message);
});
};
createUser(baseUrl, options);
You should be able, that you send right object structure to you api service. Also this seems like as the problem on the api service side

How to send a request to a Heroku app through another webpage?

I have a herokuapp deployed on heroku and it can pass all of my postman test. However, when I try to send a request to the herokuapp link through fetch using another project's button, it always fail and break the herokuapp. I'm trying to use the herokuapp as a server and it is already connected with my mongo database.
I copy pasted the code from var myHeaders straight from postman's code generating function.
Here is the code for my request, I have a username and a password input on the page and this function is designed for the sign in button:
function signin() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("username", "dandan");
urlencoded.append("password", "123");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
***mode: 'no-cors'***// This will make it work, but I don't know why
};
fetch("https://emma-game-server.herokuapp.com/signin", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
[UPDATED] I figured out adding mode:'no-cors' will give me the response, but as a noob I don't totally understand.
[UPDATED AGAIN] I figured out that I don't need 'no-cors' and I need to change the request form, here's the final alteration that worked:
function signin() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"username":username,"password":password});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://emma-game-server.herokuapp.com/signin", requestOptions)
.then(response => response.json())
.then(result => {
console.log(result);
if (result.success){
alert("Signed in as " + result.username);
document.getElementById("user").innerHTML=username;
}
else{
alert(result.message);
}
})
.catch(error => console.log('error', error));
}

Making a x-www-form-urlencoded request with axios

const { user } = require('./config');
const axios = require('axios');
const Querystring = require('querystring');
let body = Querystring['stringify']({
email: 'MY EMAIL#email.com',
password: 'pass'
})
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios['post']('https://minecraftservers.org/login', body, config)
['then'](response => console.log(response))
Im trying to login through a website
it doesn't have an api
the headers are correct
if you're wandering how i knew this, i used chrome dev tools
like reverse engineer
content-type: application/x-www-form-urlencoded
that's the header they used when i tried to login to the site
this is what i get when i logged in through the site and not the code, it works there.
You can use URLSearchParams
const params = new URLSearchParams();
params.append('firstName', 'paul');
params.append('lastName', 'fred');
axios.post('/user', params);
It avoids adding another library.
I guess systax is your problem. Do you have any difficulties other than the syntax?
const { user } = require('./config');
const axios = require('axios');
const Querystring = require('querystring');
let body = Querystring['stringify']({
email: 'MY EMAIL#email.com',
password: 'pass'
})
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios.post('https://minecraftservers.org/login', body, config)
.then(response => console.log(response))
Try
axios.post('https://minecraftservers.org/login', body, config)
.then(response => console.log(response))

How to POST a blob and JSON values using fetch

I am passing a blob image file to a server using the header,
application/octet-stream.
I need to also pass some string values to the server with it. If I change the header to
application/json
I can access the string, but the blob becomes undefined.
Example
const data = {
blob,
firstname: 'Nichoals',
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.blob())
.then(blob => {
...
})
.catch(error => console.log(error));
},
'image/png',
1,
);
Things I have tried
I have tried to pass the data using FormData() and was able to get the data to the server but the file was corrupt. I do think I could figure out how to get it to work this way but I would like to learn a better way to do it if possible.
Things I do not want to do
I do not want to convert the blob to a string because I fear that will be way to expensive.
Question
In what way can I POST an object with a blob and some string values inside of it to a server without using the way mentioned above?
Essentially this,
const data = {
blob,
firstname: 'Will',
};
You could send the json as a header:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'Custom-Json': JSON.stringify(data)
},
body: blob,
}).then(response => response.blob())
.then(blob => {
// handle response
})
.catch(error => console.log(error));

Categories