Hey guys i am trying to create search with back-end API in react native and i have to pass the word entered into the TextInput to the url. I am not sure whether i am doing it correctly or not can any body help me in rectifying
Here is the code.
this.state = {
search: "",
}
async onSearchPressed() {
try {
let response = await fetch("http://www.endpoints.com/search/{this.state.search}", {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
});
render = () => {
let fields = [
{ref: 'search', placeholder: 'search', keyboardType:'default',secureTextEntry: false},];
return (
<TextInput
{...fields[0]}
onChangeText={(val) => this.setState({search: val})}
value={this.state.search}
/>
<TouchableOpacity onPress={this.onSearchPressed.bind(this)} />
It looks like, It taken the {this.state.search} as the string.
Change
let response = await fetch("http://www.endpoints.com/search/{this.state.search}", {
to
let response = await fetch("http://www.endpoints.com/search/"+this.state.search, {
What you are trying to use is https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals.
It should go like:
fetch(`http://www.endpoints.com/search/${this.state.search}`
Related
I tried three different methods to get checksum of a same file.
1- using crypto-js (with CryptoJS.SHA1(event.target.result))
2- using sha1.min.js (with sha1(event.target.result)
3- using crypto (with crypto.subtle.digest('SHA-1', fileUint8))
Each one produces different sha1 value for same file, I don't know why.
However, sha1(event.target.result) created same checksum as produced by online sha1 calculator. I tried all values one by one in uploading but request is failed with message 'Checksum did not match data received'
If i assume that one of sha1 value is correct, then it means there is something wrong in Uppy Uploading and the file contents are not pushed properly to bucket so error message appears in response.
.....
Here is the code sample to get sha-1.
function digestFile(file) {
var reader = new FileReader();
reader.onloadend = function (event) {
if (event.target.readyState == FileReader.DONE) {
var file_sha1 = CryptoJS.SHA1(event.target.result); // first method
var file_sha2 = sha1(event.target.result); // second method
};
reader.readAsArrayBuffer(file.data);
}
third method is here
async function digestMessage1(file) {
const fileUint8 = new TextEncoder().encode(file);
const hashBuffer = await crypto.subtle.digest('SHA-1', fileUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
function digestFile(file) {
var reader = new FileReader();
reader.onloadend = function (event) {
if (event.target.readyState == FileReader.DONE) {
digestMessage1(event.target.result)
.then((digestHex) => console.log(digestHex));
};
reader.readAsArrayBuffer(file.data);
}
..
Here is the Uppy JS code.
let data = this.el.dataset;
var uppy = new UppyLib({
autoProceed: true,
allowMultipleUploadBatches: true,
restrictions: { allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png', '.gif'] }
})
uppy.use(Uppy.Dashboard, { target: '#drag-drop-area', inline: true, width: 750, height: 550})
uppy.use(AwsS3, {
getUploadParameters(file) {
return fetch('/assets/new', {
method: 'GET',
headers: { accept: 'application/json', 'content-type': 'application/json' }
}).then((response) => {
return response.json()
}).then((data) => {
return {
method: 'POST',
url: `${data.url}`,
fields: [],
headers: {
"Content-Type": "b2/x-auto",
"Authorization": `${data.token}`,
"X-Bz-File-Name": `assets/${Date.now()}-${encodeURI(file.name)}`,
"X-Bz-Content-Sha1": "94d2ff39a524e0cf20f3bd6cf909c426"
},
}
})
}
})}
I am working on a trigger where I need to pull data from two API end points. The first endpoint is a contact from a database that retrieves an email address, then to obtain the details for that contact (email) I need to use another end point. once is /Subscriber and the other is /Subsriber/ {email}/ Properties.
I am wondering if I can use a variable to obtain all the data in one trigger, as I have is set up in separate triggers right now.
Here is the code for both
Subscriber:
url: 'https://edapi.campaigner.com/v1/Subscribers?PageSize=1',
method: 'GET',
headers: {
'Accept': 'application/json',
'X-API-KEY': bundle.authData.ApiKey
},
params: {
'ApiKey': bundle.authData.ApiKey
}
};
return z.request(options).then((response) => {
response.throwForStatus();
const result = z.JSON.parse(response.content);
result.id = result.Items;
return [result];
});
And Subscriber Properties
const options = {
url: `https://edapi.campaigner.com/v1/Subscribers/${bundle.inputData.email_address}/Properties`,
method: 'GET',
headers: {
'Accept': 'application/json',
'X-API-KEY': bundle.authData.ApiKey
},
params: {
'email_address': bundle.inputData.email_address,
'ApiKey': bundle.authData.ApiKey
}
}
return z.request(options).then((response) => {
response.throwForStatus();
const result = z.JSON.parse(response.content);
result.id = result.CustomFields;
return [result];
});
Any help is appreciated.
Yes, definitely possible! Unless your subscriber data actually needs to be a separate trigger (which is unlikely, since you probably just trigger off new contacts), it can just be a function. Try something like:
const subscriberPerform = async (z, bundle) => {
const emailResponse = await z.request({
url: "https://edapi.campaigner.com/v1/Subscribers?PageSize=1",
method: "GET",
headers: {
Accept: "application/json",
"X-API-KEY": bundle.authData.ApiKey, // does this need to be both places?
},
params: {
ApiKey: bundle.authData.ApiKey, // does this need to be both places?
},
});
// requires core version 10+
const email = emailResponse.data.email;
const emailDataResponse = await z.request({
url: `https://edapi.campaigner.com/v1/Subscribers/${email}/Properties`,
method: "GET",
headers: {
Accept: "application/json",
"X-API-KEY": bundle.authData.ApiKey,
},
params: {
email_address: bundle.inputData.email_address, // lots of duplicated data here
ApiKey: bundle.authData.ApiKey,
},
});
return [emailDataResponse.data.SOMETHING];
};
That's the general idea. These JS functions may not need to be triggers at all, depending on how you're using them.
One last note - you don't want to perform this extra lookup every time you poll for new contacts; that's wasteful. If you're doing that, check out dehydration.
I have a simple zapier integration built and it works perfectly. However, I'm adding dynamic fields. Again it all seems to work perfectly when I test the zap. My dynamic form fields appear just as I expected.
The problem is sending the value of those dynamic forms to my API. I am using the zapier console and when I configure the API request I am using the following:
Where body['custom_fields'] is supposed to send all my dynamic fields or even all of the fields. But when it hits my API custom_fields parameter is blank.
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: {
'email': bundle.inputData.email,
'custom_fields': bundle.inputData
/**
I've tried the following with no luck:
'custom_fields': bundle.inputData.fields
'custom_fields': bundle.inputData.undefined
'custom_fields': bundle.inputData
*/
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
Ok after a few days, it's the simplest answer.
Obviously an object can't be sent over params.
so instead of having
'custom_fields': bundle.inputData
I just add the whole object to the params and it takes care of all keys and values
params: bundle.inputData
Here is the full body
const options = {
url: 'https://apiendpoint.com',
method: 'POST',
headers: {
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
params: bundle.inputData,
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
You can use the spread operator ...bundle.inputData like explained in the doc:
https://platform.zapier.com/docs/input-designer#how-to-include-dynamic-fields-in-api-calls
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: { ...bundle.inputData }
}
You can even namespace your request data like that:
body: {
request: { ...bundle.inputData }
}
NB : the spread operator raises a syntax error in Zapier code editor, but it works.
Hello everyone and thanks in advance ...
I'm trying to use the Contact Form7 APIs to fill in and submit a form from an Angular NativeScript App.
I have tried different solutions but I always get the same error response.
{"into":"#","status":"validation_failed","message":"Oops, there seems to be some error in the fields. Check and try again, please.","invalidFields":[{"into":"span.wpcf7-form-control-wrap.nome","message":"Attention, this field is required!","idref":null},{"into":"span.wpcf7-form-control-wrap.mail","message":"Attention, this field is required!","idref":null}]}
In the example I have entered static values in the body for convenience
Help me ;(
attempt 1
onTappedInvia(): void {
fetch("http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
nome: "Test API",
mail: "test#test.test"
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
attempt 2
deliverForm() {
var formData: any = new FormData();
formData.append('nome', "Test API");
formData.append('email', "test#test.test");
formData.append('your-message', "Test API");
this.submitted=true;
console.log(formData);
this.formService.create(formData)
.subscribe(
data => {
console.log('Invoice successfully uploaded');
console.log('Error'+ JSON.stringify(data));
},
error => {
console.log('Error'+ JSON.stringify(error));
});
console.log('USCITO');
}
and formService
const HttpUploadOptions = {
headers: new HttpHeaders({ "Content-Type": "multipart/form-data;" })
}
#Injectable({
providedIn: 'root'
})
export class FormService {
constructor(
private HttpClient: HttpClient
) { }
create(formData){
return this.HttpClient.post('http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback', formData, HttpUploadOptions)
}
}
The problem was with the Content-Type. i tried with application/x-www-form-urlencoded and it works!
fetch("http:www.aficfestival.it/wp-json/contact-form-7/v1/contact-forms/5173/feedback?", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: form
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
I wanted to send a POST request to my backend with webview. How do i get but i got the above error.
From the docs:
" headers (object) - Additional HTTP headers to send with the request. On Android, this can only be used with GET requests."
How do i get a work-around for this ?
this is my code
const data = JSON.stringify({
type: 'car',
plate_number: 'c123'
});
return (
<WebView
source={{
uri:'https://api-stg.caspian.id/user/vehicles/add',
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: '54dc3c3c*******'
},
body: data
}}
/>
);
One way to get around this limitation is by performing this POST request in the React Native side of things, waiting for this response to arrive, and then feed the response HTML into the WebView directly:
// Here using the fetch API as base, but you can use any
// library you want that is able to perform HTTP requests
constructor(props, ctx) {
super(props, ctx);
this.state = { html: null };
}
componentDidMount() {
const data = JSON.stringify({
type: 'car',
plate_number: 'c123'
});
fetch('https://api-stg.caspian.id/user/vehicles/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: '54dc3c3c*******'
},
body: data,
}).then(response => response.text()).then(text => {
this.setState({ html: text });
});
}
render() {
return this.state.html ? (
<WebView
source={{
html: this.state.html,
baseUrl: 'https://api-stg.caspian.id/user/vehicles/add',
}}
originWhitelist={['*']}
/>
) : /* loading UI */ null;
);
Here are the WebView's docs regarding the source property and how to put a static HTML in there:
https://facebook.github.io/react-native/docs/webview#source
You can use a custom extension of WebView, as described in Send Post request along with HttpHeaders on Android (see the duplicate questions for other answers).