I have a question about the code. Probably the solution is very simple, but I'm taking the first step in JavaScript and it is not obvious to me.
I have some backend ready, postman sending POST is ok. So backend is fine.
I wrote a simple application in which after pressing the button saves the given data in the database.
Unfortunately, this doesn't work with the debugger, everything is fine. However, by clicking the button in the view something is wrong and no fetch is called. The object is not saving to the database.
Please help.
Api = function() {
this.header = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
};
Api.prototype.buildUrl = function(id) {
return "http://localhost:3000/db/shop_name/" + id;
};
Api.prototype.post = function(id, data) {
const urlPost = api.buildUrl(id.value);
return fetch(urlPost, {
method: "post",
body: JSON.stringify(data),
headers: this.header
})
.then(res => res.json())
.then(res => {
console.log("Dodałem użytkownika:");
console.log(res);
})
};
Api.prototype.get = function(id) {
//const urlGet = api.buildUrl(id);
return fetch(id, {
method: "GET",
})
.then(resp => {
alert(resp.json());
return resp.json();
})
};
Api.prototype.getAlll = function() {
return fetch(url, {
method: "GET"
})
.then(resp => {
alert(resp.json());
return resp.json()
})
};
Api.prototype.update = function(id, data) {
const url = api.buildUrl(id);
return fetch(url, {
method: "PUT",
body: JSON.stringify(data)
})
.then(resp => {
return resp.json()
.catch(error => {
let notFound = "The server can not find requested resource";
document.getElementById("stars").innerHTML = notFound + error.status;
})
})
};
Api.prototype.addProduct = function(id, data) {
return this.post(id, data);
};
Api.prototype.deleteProduct = function(id) {
return this.delete(id);
};
Api.prototype.updateProduct = function(id, data) {
return this.update(id, data);
};
Api.prototype.getProduct = function(id) {
return this.get(id);
};
Api.prototype.getAllProducts = function() {
return this.getAlll;
};
const Main = function() {
this.id = document.getElementById("id");
this.addCount = document.getElementById("count");
this.addName = document.getElementById("name");
this.addPrice = document.getElementById("price");
};
Main.prototype.add = function() {
// const ido = this.id.value;
const data = {
"price": this.addPrice.value,
"name": this.addName.value,
"count": this.addCount.value,
};
// let id = api.buildUrl(this.id.value);
api.addProduct(this.id, data);
};
Main.prototype.update = function() {
const data = {
"price": this.price,
"name": this.name,
"count": this.count,
};
api.updateProduct(id, data);
};
Main.prototype.delete = function() {
let id = api.buildUrl(this.id);
api.deleteProduct(id);
};
Main.prototype.get = function() {
let id = api.buildUrl(this.id.value);
api.getProduct(id);
};
Main.prototype.getAll = function() {
api.getAllProducts();
};
const api = new Api();
const main = new Main();
let addButton = document.getElementById('postBtn');
addButton.addEventListener('click', function() {
main.add();
});
/*
addButton.addEventListener("click",main.add.bind(main));
*/
let updateButton = document.getElementById("updateBtn");
updateButton.addEventListener("click", function() {
main.update();
});
let deleteButton = document.getElementById("deleteBtn");
deleteButton.addEventListener("click", function() {
main.delete();
});
let getButton = document.getElementById("getBtn");
getButton.addEventListener("click", function() {
main.get();
});
let getAllButton = document.getElementById("getAllBtn");
getAllButton.addEventListener("click", function() {
let tst = main.getAll();
console.log(tst);
});
Related
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 struggling with the Response of the Javascript fetch() method. What is my objective: a) to send multiple lines to the backend to save those to a database and b) get a guid in return for further processing.
I succeed in objective a (save to database), but the return message fails to materialise. Response.ok is true, but no message is part of the return message.
What should I do to accomplish this?
My javascript is:
function saveAll(event) {
event.preventDefault();
var newDeelnemers = new Array();
var lijst = document.querySelectorAll('#tblDeelnemers tbody tr')
lijst.forEach(function (dnmr) {
var row = dnmr;
var deelnemer = {};
var nDnmr = row.children;
//deelnemer.Id = nDnmr[0].innerHTML;
deelnemer.FamilielidFirstName = nDnmr[0].innerHTML;
deelnemer.Achternaam = nDnmr[1].innerHTML;
deelnemer.DOB = nDnmr[2].innerHTML;
deelnemer.Programma = nDnmr[3].innerHTML;
deelnemer.EetMee = nDnmr[4].firstChild.checked;
deelnemer.Dieet = nDnmr[5].innerHTML;
deelnemer.Bedrag = nDnmr[6].innerHTML;
newDeelnemers.push(deelnemer);
});
fetch("/Familiedag/Registreer", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newDeelnemers)
}).then(function (response) {
console.log('eerste keer: ' + response);
if (response.ok) {
alert('De registratie is gelukt');
//redirect("/Familiedag/RegistreerConfirm?")
}
});
}
The controller
[HttpPost]
public IActionResult Registreer([FromBody] List<FdDeelnemer> newDeelnemers)
{
if (newDeelnemers.Count == 0)
{
return null;
}
Guid registratieGuid = Guid.NewGuid();
foreach (var ndn in newDeelnemers)
{
FdDeelnemer VM = new FdDeelnemer();
VM.RegistratieGuid = registratieGuid;
VM.FamilielidFirstName = ndn.FamilielidFirstName;
VM.Achternaam = ndn.Achternaam;
VM.EetMee = ndn.EetMee;
VM.Dieet = ndn.Dieet;
VM.Programma = ndn.Programma;
VM.DOB = ndn.DOB;
VM.Bedrag = ndn.Bedrag;
VM.CreatedBy = User.Identity.Name;
VM.CreatedOn = DateTime.UtcNow;
_context.Add(VM);
}
Guid geregistreerdeDeelnemers = registratieGuid;
return Json(geregistreerdeDeelnemers);
}
add another .then that return the json
fetch("/echo/json/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"tes": "data"
})
}).then(function(response) {
return response.json();
}).then(function(json) {
console.log('eerste keer: ', json);
alert('De registratie is gelukt');
//redirect("/Familiedag/RegistreerConfirm?")
});
You can try to return it like that:
return Json(new { AnythingYouWant = geregistreerdeDeelnemers });
I am currently attempting to get an image upload component built in Zapier but am having issues getting it to work. I have to be able to download an image, and then POST it to a new endpoint without storing it locally. Currently, the closest I've been able to do is get an IncomingMessage to POST, but I know that's not right.
Does anyone have any advice?
let FormData = require('form-data');
let http = require('https');
const makeDownloadStream = (url) => {
new Promise((resolve, reject) => {
http.request(url, resolve).on('error', reject).end();
});
}
const makeUploadStream = (z, bundle, options) => {
var imageRequest = options;
const promise = z.request(imageRequest);
return promise.then((response) => {
return response.data;
});
}
const addAttachment = async (z, bundle) => {
/*var request = {
'url': bundle.inputData.attachment
};
const promiseAt = z.request(request);
return promiseAt.then((stream) => {*/
const form = new FormData();
var data = `{"type": "records", "attributes": {"form_id": ${bundle.inputData.form_id}}}`
const stream = await makeDownloadStream(bundle.inputData.attachment);
form.append(`field_${bundle.inputData.field_id}`, stream);
form.append('data', data);
var request = {
'url': bundle.inputData.url,
'method': 'PUT',
'headers': {
'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`
},
'body': form
};
const response = await makeUploadStream(z, bundle, request);
return response;
//});
}
I figured it out myself. For anyone needing to upload an image on Zapier, here it is:
let FormData = require('form-data');
const makeDownloadStream = (z, bundle) => {
var imageRequest = {
'url': bundle.inputData.attachment,
'method': 'GET',
'raw': true
};
const promise = z.request(imageRequest);
return promise.then(async (response) => {
var buffer = await response.buffer();
return {
'content-type': response.headers.get('content-type'),
'content': buffer,
'filename': response.headers.get('content-disposition').replace('attachment; filename="', '').replace('"', '')
}
});
}
const addAttachment = async (z, bundle) => {
const form = new FormData();
const content = await makeDownloadStream(z, bundle);
form.append(`field_${bundle.inputData.field_id}`, Buffer.from(content.content.toString('binary'), 'binary'), {
filename: content.filename
});
const request = {
'url': `${bundle.inputData.url}/api/records/${bundle.inputData.record_id}`,
'method': 'PUT',
'headers': {
'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`,
'Content-Length': form.getLengthSync()
},
'body': form
};
const promise = z.request(request);
return promise.then((response) => {
return response.data;
});
}
I need to pull inventory data to my NextJS app, I am then trying to store that data to localStorage, but it never gets set. What am I doing wrong?
if (process.browser && localStorage.getItem('inv') === undefined) {
const inv = await getInventory()
localStorage.setItem('inv', inv)
}
getInventory() is just a node script that pulls inventory data from a remote api and returns fullInventory.
Here is the code from getInventory():
const getInventory = async () => {
const token = await refreshToken()
const header = {
Authorization: `Bearer ${token}`,
};
const queries = await getQueriesCount();
axios.interceptors.response.use(function (response) {
return response;
}, async function (error) {
await new Promise(function (res) {
setTimeout(function () { res() }, 2000);
});
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshedHeader = await setHeader()
axios.defaults.headers = refreshedHeader
originalRequest.headers = refreshedHeader
return Promise.resolve(axios(originalRequest));
}
return Promise.reject(error);
});
let fullInventory = [];
for (let i = 0; i < queries; i++) {
setTimeout(async () => {
try {
const res = await axios({
url: `${MyApi}/Item.json&offset=${i * 100}&customSku=!~,`,
method: "get",
headers: header,
});
console.log(`adding items ${i * 100} through ${(i + 1) * 100}`);
const items = await res.data.Item;
items[0]
? (fullInventory = fullInventory.concat(items))
: fullInventory.push(items);
if (i + 1 === queries) {
return fullInventory;
}
} catch (error) {
console.error("We have a problem here: ", error.response);
}
}, 2000 * i);
};
}
I have to functions called: getMatchDataApi() and saveApiDataToDb(). getMatchDataApi() function returns value from an api and saveApiDataToDb() function is used to store getMatchDataApi() value into firestore database.
function getMatchDataApi() {
var options = {
method: "GET",
hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
port: null,
path: "/scorecards.php?seriesid=2141&matchid=43431",
headers: {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
},
json: true
};
var req = http.request(options, res => {
var chunks = [];
res.on("data", chunk => {
chunks.push(chunk);
});
res.on("end", () => {
var body = Buffer.concat(chunks);
var json = JSON.parse(body);
playerName = json.fullScorecardAwards.manOfTheMatchName;
console.log("player name", playerName);
});
});
req.end();
}
async function saveApiDataToDb() {
await getMatchDataApi();
var name = playerName;
console.log("Aman Singh", name);
}
Here i am using async function. So that first i want it should execute this getMatchDataApi() first and returns the value and after that it should print value inside this function saveApiDataToDb().
And then i am calling saveApiDataToDb() as follow:
exports.storeMatchData = functions.https.onRequest((request, response) => {
saveApiDataToDb()
});
Yes, you can use async/await in cloud functions. But, you can't access/fetch the data outside the google servers in the Spark Plan (Free Plan).
Hope this helps.
Modify your functions/index.js file like this way:
const functions = require('firebase-functions');
const request = require('request');
exports.storeMatchData = functions.https.onRequest( async (req, res) => {
let body = '';
await getMatchDataApi().then(data => body = data).catch(err => res.status(400).end(err));
if (!body) {
return res.status(404).end('Unable to fetch the app data :/');
}
// let json = JSON.parse(body);
// playerName = json.fullScorecardAwards.manOfTheMatchName;
// console.log("Aman Singh", playerName);
res.send(body);
});
function getMatchDataApi() {
const options = {
url: 'https://dev132-cricket-live-scores-v1.p.rapidapi.com/scorecards.php?seriesid=2141&matchid=43431',
headers: {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
},
};
return cURL(options);
}
function cURL(obj, output = 'body') {
return new Promise((resolve, reject) => {
request(obj, (error, response, body) => {
if (error)
reject(error);
else if (response.statusCode != 200)
reject(`cURL Error: ${response.statusCode} ${response.statusMessage}`);
else if (response.headers['content-type'].match(/json/i) && output == 'body')
resolve(JSON.parse(body));
else if (output == 'body')
resolve(body);
else
resolve(response);
});
});
}
I try to solve my issue using promise in cloud functions. so it could help someone.
This is my cloud function
exports.storeMatchData = functions.https.onRequest((request, response) => {
a().then(
result => {
saveApiDataToDb(result);
},
error => {}
);
});
This is the function from which i am calling api and resolving its data first what i want
var options = {
method: "GET",
hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
port: null,
path: "/scorecards.php?seriesid=2141&matchid=43431",
headers: {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
},
json: true
};
var options1 = {
method: "GET",
hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
port: null,
path: "/matches.php?completedlimit=5&inprogresslimit=5&upcomingLimit=5",
headers: {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
}
};
var a = function getMatchDataApi() {
// Return new promise
return new Promise((resolve, reject) => {
// Do async job
let firstTask = new Promise((resolve, reject) => {
var req = http.request(options, res => {
var chunks = [];
var arr = [];
res.on("data", chunk => {
chunks.push(chunk);
});
res.on("end", () => {
var body = Buffer.concat(chunks);
var json = JSON.parse(body);
const playerName = json.fullScorecardAwards.manOfTheMatchName;
resolve(playerName);
});
});
req.end();
});
let secondTask = new Promise((resolve, reject) => {
var req = http.request(options1, res => {
var chunks = [];
var arr = [];
res.on("data", chunk => {
chunks.push(chunk);
});
res.on("end", () => {
var body = Buffer.concat(chunks);
var json = JSON.parse(body);
const playerName = json;
resolve(playerName);
});
});
req.end();
});
Promise.all([firstTask, secondTask]).then(
result => {
resolve(result);
},
error => {
reject(error);
}
);
});
};
This is the function in which I am going to use getMatchDataApi() values after resolving in this function.
function saveApiDataToDb(data) {
console.log("Name of player", data[0]);
}