// Function to delete the data
app.delete("/api/theTasks/:id", (req, res) => {
let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
let index = Items.indexOf(taskToRemove);
Items.splice(index, 1);
res.json(taskToRemove);
});
Please, my application is deleting my last entries instead of the
desired data. Please, could you help? unsure, how to pass the
variable in the URL? I believe I should delete the data based on the
ID which should be in the URL as a parameter but, It doesn't work for
me
const URL = "http://localhost:5050/api/theTasks/";
const init = () => {
getDataa();
document.querySelector("#newTask").addEventListener("click", addNewTask);
//addNewTask();
};
/* The method to add a task entered by the user
*/
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "http://localhost:5050/api/theTasks/";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let taskDescription = document.querySelector("#task").value;
let theTask = taskDescription;
let params = {
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {}
}
xhr.send(JSON.stringify(params));
console.log("Display the data");
getDataa();
};
/* The method to Get the data from th API
*/
const getDataa = () => {
console.log("get Data")
fetch(URL, {
method: "GET",
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S"
}
})
.then(resp => resp.json())
.then(function(Items) {
console.log(Items);
// Loop to access all rows
let text = '';
Array.from(Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item) {
let theTask = item.Description;
let taskToRemove = Items.id;
text += ` <button type="button" class="btn" id="task2" onclick="deleteData('${theTask}')"> <i class="fa fa-trash"></i> </button> ${theTask}<br>`;
}
})
.catch(function(error) {
console.log(error);
});
}
- Here's my code for my own API that I have created using the POSTMAN
API ... is there an issue with that?
<!-- begin snippet: js hide: false console: true babel: false -->
/* the method to delete the data
*/
async function deleteData(taskDescription) {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
let url = "http://localhost:5050/api/theTasks/:";
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
You are already sending the taskDescription to the delete function. Now you just need to add the ID of whatever you are deleting to that same function and append it to the url of the endpoint in the fetch.
async function deleteData(taskDescription, elementID) {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
//add the id here
let url = `http://localhost:5050/api/theTasks/:${elementID}`;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
Related
I have an issue with my javaScript code as the delete feature is working but, it is not deleting the right data ...
Example:
1 - test1
2 - test2
3 - test3
My issue is when I try to delete test1, the program deletes test3 which means the program always deletes the last data in the list.
Please, could you help?
Here's my code:
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
let theTask = [];
let text = '';
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
addNewTask();
getDataa();
};
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let theTask = taskDescription;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
}
}
xhr.send(JSON.stringify(params));
getDataa();
};
const getDataa = () => {
console.log("get Data")
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (i = 0; i <= data.ScannedCount; i++) {
let text = '';
//const items = data.Items[i].Description;
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item, index) {
theTask= data.Items[index].Description;
text += ' <button type="button" class="btn" id="task2" onclick="deleteData()"> <i class="fa fa-trash"></i> </button> '+ " " + data.Items[index].Description + "<br>";
}
}
})
.catch(function(error) {
console.log(error);
});
}
async function deleteData() {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
let taskDescription = theTask;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
window.onload = init;
let taskDescription = theTask; always gets the last value that was ever assigned to theTask. You should make the task a parameter to the deleteData() function.
text and theTask don't need to be global variables.
I'm not sure why you have the loop for (let i = 0; i <= data.ScannedCount; i++). You never use i in the loop.
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
addNewTask();
getDataa();
};
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let theTask = taskDescription;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {}
}
xhr.send(JSON.stringify(params));
getDataa();
};
const getDataa = () => {
console.log("get Data")
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (let i = 0; i <= data.ScannedCount; i++) {
let text = '';
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item) {
let theTask = item.Description;
text += ` <button type="button" class="btn" id="task2" onclick="deleteData('${theTask}')"> <i class="fa fa-trash"></i> </button> ${theTask}<br>`;
}
}
})
.catch(function(error) {
console.log(error);
});
}
async function deleteData(taskDescription) {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
window.onload = init;
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
//document.querySelector("#deleteTask").addEventListener("click", deleteData);
getDataa();
};
const getDataa = () => {
addNewTask();
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (i = 0; i <= data.ScannedCount; i++) {
let text = "";
//const items = data.Items[i].Description;
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item, index) {
text += ' <button type="button" class="btn" id="task" onclick="deleteData()"><i class="fa fa-trash"></i></button>' + " " + data.Items[index].Description + "<br>";
}
}
})
.catch(function(error) {
console.log(error);
});
}
const deleteData = () => {
console.log("delete data ");
//let deleteDescription = document.querySelector("#task").value;
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: {
'StudentId': 'studentId',
'Description': 'taskDescription',
'version': 'JSON',
}
})
.then(res => {
if (res.ok) {
console.log("DELETE request successful");
getDataa();
return res
} else {
console.log("DELETE request unsuccessful");
}
return res
})
.then(res => res.json())
.then()
.catch(error => console.log(error))
}
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log("New record was added ...");
}
}
xhr.send(JSON.stringify(params));
};
window.onload = init;
Please, could you help with the delete function is not working as expected
Please, see attached file
Your code is sending an Object in the body
You're also setting the values of the properties to the literal strings 'studentId' and 'taskDescription'
The following may fix your issue
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
})
I am getting the error data: { success: false, error: 'Not logged in: Invalid signature' } for /wallet/balances. Interestingly, the same code runs for /wallet/coins and /markets for FTX REST API. The code is in JS
PLEASE HELP!!
const url = "https://ftx.us/api/wallet/balances"
const path = "/api/wallet/balances"
const timestamp = Date.now()
const method = "GET"
const payload = `{timestamp}{method}{url}`
const hash = CryptoJS.HmacSHA256(payload, process.env.FTX_API_SECRET)
// var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, "Secret Passphrase");
// hmac.update(JSON.stringify(timestamp));
// hmac.update(method);
// hmac.update(path);
// var hash = hmac.finalize();
const hash2 = crypto.createHmac('sha256', process.env.FTX_API_SECRET).update(payload).digest("hex")
console.log("API KEY ", process.env.FTX_API_KEY)
axios({
method: "get",
headers: {
"FTXUS-SIGN": CryptoJS.enc.Hex.stringify(hash),
// "FTXUS-SIGN": hash2,
"FTXUS-KEY": process.env.FTX_API_KEY,
"FTXUS-TS": timestamp,
},
url: url
})
.then( (response) => {
if (response.data.success) {
callback(null, response.data.result)
} else {
// error handling here for the api
callback(result.data.error)
}
})
.catch ( (e) => {
console.log("exception in request ", e)
})
add these 2 lines in headers,
{
"FTXUS-SIGN": CryptoJS.enc.Hex.stringify(hash),
"FTXUS-KEY": process.env.FTX_API_KEY,
"FTXUS-TS": timestamp,
"Content-Type": "application/json",
"Accepts": "application/json",
}
It worked for me
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")}}`
);
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
}
}