I am creating an email app that sends messages to other people. Currently, I have it working except for the recipients column. Right now, I hard-coded an email into the recipients column to get it working. The reason is, is the recipients field is supposed to be an array.
What's the best way of passing a value from a user form (multiple addresses separated by commas) into JSON format?
Below is how I have it now.
Thanks!
const element = document.getElementById('sendEmail');
element.addEventListener('click', function() {
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: 'card51short#gmail.com',
subject: document.querySelector('#compose-subject').value,
body: document.querySelector('#compose-body').value
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
});
}
const element = document.getElementById('sendEmail');
element.addEventListener('click', function() {
const emailsFromForm = [ // NEW
document.querySelector('#email1').value, // NEW
document.querySelector('#email2').value // NEW
] // NEW
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: emailsFromForm, // EDITED
subject: document.querySelector('#compose-subject').value,
body: document.querySelector('#compose-body').value
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
});
}
Related
I have a problem to find the correct dynamic variable in woocommerce which works with this API,In this API i need to send product Id and Order count which i dont know the correct variable for them in woocommerce.
please tell me the correct dynamic variable of Product ID and Order count in woocommerce.
This is my API:
const options2 = {
method: 'POST',
headers: {
"SettleTypeId": `STID`,
"RRN": `RNN`,
"ApMerchantId:": `MerchantID`,
"Products":
[
{
"ProductId":`${?}`,
"OrderCount":`${?}`
}
]
}
};
fetch('URL', options2)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
You can use Localstorage for that. You can Store productID and Order Count in localStorage and get here.
const options2 = {
method: 'POST',
headers: {
"SettleTypeId": `STID`,
"RRN": `RNN`,
"ApMerchantId:": `MerchantID`,
"Products":
[
{
"ProductId":`${localStorage.getItem("ID")}`,
"OrderCount":`${localStorage.getItem("OrderCount")}`
}
]
}
}
fetch(URL, data)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error.response.data);
});
Thanks!
I need to capture the cartID in a js variable from a JSON response.
So far I have the following code which requests the cart information.
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
The console.log data is formatted like this:
Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me#gmail.com", ................. }]
I have tried various methods to capture the cart ID to variable cartID, but each time it shows 'unknown' and is logged before the data response.
Any ideas how to delay until the response is ready and then 'cartID' with the id value?
Because the response if a JSON array, you can try to loop and extract the cartID from each cart object:
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(
data => {
//The response is an array of cart objects. We need to extract the ID from the array
cartID = data[0].id;
//Or loop through the response and extract the ID from each cart object
for (var i = 0; i < data.length; i++) {
cartID = data[i].id;
}
}
)
.catch(error => console.error(error));
I have this fetch request below, and variables data_type and data_subtype. I want to pass the value of data_type and data_subtype in the place of :type and :subtype respectively, without actually writing the variable values in there.
fetch('http://localhost:3000/feature/type/:type/subtype/:subtype,{
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
You can replace with the variable values in the URL.
eg.
const data_type = 'data Type'
const data_subtype = 'data subtype
fetch(`http://localhost:3000/feature/type/${data_type}/subtype/${data_subtype}`,{
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
as expanding the #junkie answer, you should put your url request in string literal so where you can use variables which will conditionaly replace the values without actually writing values in there, so just define and replace them.
I'm sending a post request from vue.js project using Axios and it contains a file upload, which requires me to use FormData, I found a nice answer that helped me with FormData:
const getFormData = object => Object.keys(object).reduce((formData, key) => {
formData.append(key, object[key]);
return formData;
}, new FormData());
and for the headers: headers: { 'Content-Type': 'multipart/form-data'}.
The POST call looks like this:
axios.post("http://127.0.0.1:8000/api/document/",
getFormData(this.documentData),
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log("Successfully uploaded: ", response.data)
})
.catch(err => {
console.log("error occured: ", err)
})
This is the data I'm sending:
documentData: {
name: '',
file: '',
version: '',
company: '',
author: '',
category: []
}
When sending the data with single category id, it works fine, but when I send multiple category ids the following error shows:
"category": [
"Incorrect type. Expected pk value, received str."
]
How can I solve this problem?
Assuming your server-side process is expecting multiple, repeated field names for array types, you'll want something like this
const getFormData = object => Object.entries(object).reduce((fd, [ key, val ]) => {
if (Array.isArray(val)) {
val.forEach(v => fd.append(key, v))
} else {
fd.append(key, val)
}
return fd
}, new FormData());
Some server-side processes (PHP for example) require that collection-type fields include a [] suffix. If that's what you're working with, change this line
val.forEach(v => fd.append(`${key}[]`, v))
Also, when sending FormData from your browser, do not manually set the Content-type header. Your browser will do this for you, including the required boundary tokens
axios.post("http://127.0.0.1:8000/api/document/", getFormData(this.documentData))
.then(response => {
console.log("Successfully uploaded: ", response.data)
})
.catch(err => {
console.error("error occurred: ", err)
})
you can use json stringfy ,
I am using it also with vue app
formData.append("TeamMembers", JSON.stringify(this.TeamMembers));
axios
.post("/api/pro", formData, {
onUploadProgress: (progressEvent) => console.log(progressEvent.loaded),
headers: { "Content-Type": "multipart/form-data", }, })
Team members is an array .. and you can parse it in the other side this way
const myArr = ['bacon', 'lettuce', 'tomatoes'];
const myArrStr = JSON.stringify(myArr);
console.log(myArrStr);
// "["shark","fish","dolphin"]"
console.log(JSON.parse(myArrStr));
// ["shark","fish","dolphin"]
Object array passes values
var arr=['上海','北京'];
var formData = new FormData();
for (var i = 0; i < arr.length; i++) {
formData.append('city[]',arr[i]);
}
I'm trying to make a POST request with a GraphQL query, but it's returning the error Must provide query string, even though my request works in PostMan.
Here is how I have it running in PostMan:
And here is the code I'm running in my application:
const url = `http://localhost:3000/graphql`;
return fetch(url, {
method: 'POST',
Accept: 'api_version=2',
'Content-Type': 'application/graphql',
body: `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
Any ideas what I'm doing wrong? Is it possible to make it so that the body attribute I'm passing in with the fetch request is formatted as Text like I've specified in the PostMan request's body?
The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.
This should work in your case:
const url = `http://localhost:3000/graphql`;
const query = `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
return fetch(url, {
method: 'POST',
Header: {
'Content-Type': 'application/graphql'
}
body: query
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
This is how to submit GraphQL variables:
const query = `
query movies($first: Int!) {
allMovies(first: $first) {
title
}
}
`
const variables = {
first: 3
}
return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
return data
})
.catch((e) => {
console.log(e)
})
I created a complete example on GitHub.