I have a form code that the api is a PUT method, I have a part where I have to send it in the form of a objects, but when I send it it sends it to me as an array, they also tell me that I have to send them if it is true or false
handleSubmit = async (event) => {
const {
state,
city,
mild_symptoms = [],
} = event
const YES = "Si"
console.log(event)
try {
const myHeaders = new Headers();
const url =
"XXXXXXXXX";
myHeaders.append(
"x-api-key",
"XXXXX"
);
myHeaders.append("state", state);
myHeaders.append("city", city);
myHeaders.append(
"mild_symptoms",
`{"flu_syndrome": ${mild_symptoms.includes("flu_syndrome")}, "conjunctivitis": ${mild_symptoms.includes("conjunctivitis")}, "muscle_pain": ${mild_symptoms.includes("muscle_pain")}}`
);
var requestOptions = {
method: "PUT",
headers: myHeaders,
mode: "cors"
};
const response = await fetch(url, requestOptions);
console.log("FIRST RESPONSE ", response);
const result = await response.text();
console.log("RESULT", result);
Modal.success({
title: "Éxito",
content: "Datos enviados correctamente",
onOk: ()=>{
window.location.href = "https://covid19.gob.sv/orientaciones-tecnicas/"
}
})
} catch (error) {
console.log("ERROR", error);
}
I have to send this as a objects and not as an array
"mild_symptoms",
`{"flu_syndrome": ${mild_symptoms.includes("flu_syndrome")}, "conjunctivitis": ${mild_symptoms.includes("conjunctivitis")}, "muscle_pain": ${mild_symptoms.includes("muscle_pain")}}`
);
Related
Hi i'm using MeaningCloud's api to get the proper object back once it analyses a string of text or a url for the Natural language processing (NLP). But it doesn't return the proper object.
Right now the code returns a string with the text "[Object object]" on the HTML page. I need it to return the results of the api call which returns the proper JSON object(that I can see in the console) in a proper "key/value" pair format on the HTML page.
Here's my script:
const baseURL = "https://api.meaningcloud.com/sentiment-2.1";
const key = "Your_api_key";
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const url = document.getElementById("url").value;
if (url !== "") {
getData(baseURL, url, key)
.then(function (data) {
postData("/add", { data: data });
}).then(function () {
receiveData()
}).catch(function (error) {
console.log(error);
alert("Invalid input");
})
}
})
const getData = async (baseURL, url, key) => {
const res = await fetch(`${baseURL}?key=${key}&txt=${url}`)
try {
const data = await res.json();
return data;
}
catch (error) {
console.log("error", error);
}
}
const postData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: data
})
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log(error);
}
};
const receiveData = async () => {
const request = await fetch('/all');
try {
// Transform into JSON
const allData = await request.json()
console.log(allData)
// Write updated data to DOM elements
document.getElementById('result').innerHTML = allData;
}
catch (error) {
console.log("error", error);
// appropriately handle the error
}
}
I have another main file that's the server.js file which I run using node server.js that renders the html page properly but the script doesn't render the results on the page properly. You can signup on meaningcloud for a free api key that has a very convenient number of calls you can make.
I'm having trouble sending data to the Backend. I want to send data f1 to QueryBackend.js but when I try to console.log(req.body.f1) it's always undefined but in Services.js get the value.
Toolbar.js
handlePrintLetter = async(fieldName, fieldValue) => {
const { formId, selectedRows, displayData, onNotification } = this.props;
const idSelected = selectedRows.data.map(d => displayData[d.dataIndex].id);
const res = await getBookmarkDocument(idSelected); // Send Data to Backend
if (res.success) {
onNotification({ mode: 'success', text: 'success' });
} else {
onNotification({ mode: 'error', text: fieldName + ' ' + fieldValue });
}
}
Service.js
export const getBookmarkDocument = async (f1) => {
console.log(f1) // get value from Toolbar.js
const token = localStorage.getItem('token');
return axios.get(API + 'doc/show', { f1 },
{
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => response.data || [])
.catch((error) => {
ErrorAPI(error);
return [];
});
}
How to get data f1 in here?
QueryBackend.js
router.get('/show', async (req, res) => {
try {
console.log(req.body.f1) // undefined
const pool = await poolPromise;
const result = await pool.query('SELECT sid_ddocument_key FROM sid_ddocument WHERE sid_ddocument_key = $1', ['I WANNA PUT DATA 'f1' IN HERE']); // Put Data f1
res.status(200).json({
success: true,
data: result.rows
});
} catch (err) {
res.status(500).json({
success: false,
response: err.message
});
}
});
GET requests can't have bodies. Encode the data in the query string and read it with req.query
const f1 = 'example';
const API = 'http://example.com/';
const url = new URL(`${API}doc/show`);
url.searchParams.append("f1", f1);
console.log(url.toString());
I'm trying to chain two async functions but it seems that the second one is being executed before the first one.
Here is my code
function performAction(e) {
const ZIP = document.getElementById('zip').value;
const fellings = document.getElementById('feelings').value;
console.log(`${baseURL}${ZIP},us&appid=${key}`);
getWeather(baseURL, ZIP, key,).then((data) => {
postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
}).then(
updateUI()
)}
and This is getWeather()
const getWeather = async(baseURL, ZIP, key) => {
let URL = `${baseURL}${ZIP}&appid=${key}`;
const res = await fetch(URL)
try{
const data = await res.json();
return data;
}catch(error){
console.log("error", error);
}}
and this is postData() which is supposed to execute after the getWeather function is excuted but it isn't.
const postData = async ( url = '', data = {}) => {
console.log(`This is what we fetch ${data.temperature}`);
console.log(`This is what we fetch ${data.date}`);
console.log(`This is what we fetch ${data.userResponse}`);
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
// Body data type must match "Content-Type" header
body: JSON.stringify(data),
});
try {
const newData = await response.json();
console.log(`This is the new Data ${newData.temperature}`);
return newData;
}catch(error){
console.log("error", error);
}}
and this is updateUI()
const updateUI = async () => {
const request = await fetch('/getweather');
try{
const allData = await request.json();
console.log('Get request');
document.getElementById('date').innerHTML = allData.date;
document.getElementById('temp').innerHTML = allData.temperature;
document.getElementById('content').innerHTML = allData.userResponse;
}catch(error){
console.log("error", error);
}}
What happens is that the UI gets updated first so it gets the value of undefined for the first time, and when I reload the page and enter new data the UI get's updated with the data from last time.
You need to return the promise returned from postData:
getWeather(baseURL, ZIP, key,).then((data) => {
return postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
}).then(() => {
return updateUI()
})
Another way you could write this is like this:
async function run() {
await getWeather(baseURL, ZIP, key)
await postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
await updateUI()
}
your postData() is also an async function. Therefore you have to await this aswell:
getWeather(baseURL, ZIP, key,).then(async (data) => {
await postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
}).then(
updateUI()
)}
I didn't have done javascript in a while, but i guess it is more clear in this way:
const performAction = async (e) => {
const ZIP = document.getElementById('zip').value;
const fellings = document.getElementById('feelings').value;
console.log(`${baseURL}${ZIP},us&appid=${key}`);
try{
const data = await getWeather(baseURL, ZIP, key,);
const postData= await postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings });
} catch(e) {
console.log(e)
} finally {
updateUI();
}
Also you dont have to await the parsing of the json and the try catch should contain your request:
const postData = async ( url = '', data = {}) => {
console.log(`This is what we fetch ${data.temperature}`);
console.log(`This is what we fetch ${data.date}`);
console.log(`This is what we fetch ${data.userResponse}`);
try {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
// Body data type must match "Content-Type" header
body: JSON.stringify(data),
});
const newData = response.json();
console.log(`This is the new Data ${newData.temperature}`);
return newData;
}catch(error){
console.log("error", error);
}}
Why i got output "\"userName\"" and not as "userName" ?
in my example i try to do an get api that attach to it some data and that data comes from the async-storage.
when i console the output so its shows the data like that :
"\"userName\""
but it should output "userName" .
what is the way to fix that issue ?
so what is wrong in my way ?
const getSaveUserTokenData = async (data) => {
const url =
'https://URL/userName,userToken,PlatformType,DeviceID?' +
'userName=' +
data.userName +
'&userToken=' +
data.googlToken +
'&PlatformType=' +
data.platformId +
'&DeviceID=' +
data.deviceId;
await fetch(
url,
{
method: 'GET',
headers: {
Authorization: data.azureToken,
},
}
)
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
You can write this way as well:
fetchFunction = async () => {
let data = {
userName: 'jon',
userToken: 'bee22',
PlatformType: 'os-ios',
DeviceID: '222222'
}
const url = `https://yoururl.com/?userName=${encodeURIComponent(data.userName)}&userToken=${encodeURIComponent(data.userToken)}&PlatformType=${encodeURIComponent(data.PlatformType)}&DeviceID=${encodeURIComponent(data.DeviceID)}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': 'Basic ' + btoa('username:password'),
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
const json = await response.json();
console.log(json);
}
If your variable names are the one you want in your url, try this:
const getData = async () => {
let userName = 'jon';
let userToken = 'bee22';
let PlatformType = 'os-ios';
let DeviceID = '222222';
const queryString = Object.entries({
userName,
userToken,
PlatformType,
DeviceID,
})
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
const response = await fetch(
'https://url...?' + queryString
);
};
};
Note: user token should not be in the url but usually in the headers of your request, like so:
fetch(someUrl, {
headers: {
Authorization: userToken
}
});
fetch(`https://yoururl.com/${userName}`,
{ method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default'
})
.then(function(response) {
//your code here
});
A more generic solution would be something like this:
async function get(route, ...params) {
const url = `${route}${params.map(p => `/${p}`)}`;
const response = await fetch(url, { method: "GET", headers });
if (!response.ok)
throw new Error(`Http error status: ${response.status}`);
return response.json();
}
by using ...params you can pass a generic amount of parameters that will then be combined with:
const url = `${route}${params.map(p => `/${p}`)}`;
In your case you would call the method like this:
const result = await get("https://url..", "jon", "bee22", "os-ios", "222222");
Hello after setup a simple async function with promise return i'd like to use then promise instead of try!
But is returning
await is a reserved word
for the second await in the function.
i've tried to place async return promise the data! but did not worked either
async infiniteNotification(page = 1) {
let page = this.state.page;
console.log("^^^^^", page);
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch(`/notifications?page=${page}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
params: { page }
})
.then(data => data.json())
.then(data => {
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch("/notifications/mark_as_read", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
body: JSON.stringify({
notification: {
read: true
}
})
}).then(response => {
this.props.changeNotifications();
});
})
.catch(err => {
console.log(err);
});
}
> await is a reserved word (100:25)
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
^
fetch("/notifications/mark_as_read", {
You should refactor how you make your requests. I would have a common function to handle setting up the request and everything.
const makeRequest = async (url, options, auth_token) => {
try {
// Default options and request method
if (!options) options = {}
options.method = options.method || 'GET'
// always pass a body through, handle the payload here
if (options.body && (options.method === 'POST' || options.method === 'PUT')) {
options.body = JSON.stringify(options.body)
} else if (options.body) {
url = appendQueryString(url, options.body)
delete options.body
}
// setup headers
if (!options.headers) options.headers = {}
const headers = new Headers()
for(const key of Object.keys(options.headers)) {
headers.append(key, (options.headers as any)[key])
}
if (auth_token) {
headers.append('Access', auth_token)
}
headers.append('Accept', 'application/json')
headers.append('Content-Type', 'application/json')
options.headers = headers
const response = await fetch(url, options as any)
const json = await response.json()
if (!response.ok) {
throw json
}
return json
} catch (e) {
console.error(e)
throw e
}
}
appendQueryString is a little helper util to do the get qs params in the url
const appendQueryString = (urlPath, params) => {
const searchParams = new URLSearchParams()
for (const key of Object.keys(params)) {
searchParams.append(key, params[key])
}
return `${urlPath}?${searchParams.toString()}`
}
Now, to get to how you update your code, you'll notice things become less verbose and more extensive.
async infiniteNotification(page = 1) {
try {
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
const data = await makeRequest(
`/notifications`,
{ body: { page } },
auth_token
)
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
const markedAsReadResponse = makeRequest(
"/notifications/mark_as_read",
{
method: "POST",
body: {
notification: { read: true }
},
auth_token
)
this.props.changeNotifications();
} catch (e) {
// TODO handle your errors
}
}