prevent multiple http request send by using fetch - javascript

I'm creating a chrome extension, in which I take input from using prompt and send it to the server using an HTTP request. By doing this I'm facing duplication of data, which means the extension is sending multiple requests to the server, which I want to prevent. (Note: by taking data from prompt only once it is sending multiple requests of same data)
Example code:
Front-End:
var data = prompt("Enter your data here");
if (data !== null || data !== ''){
fetch('http://localhost:3000/post', {
method: 'POST',
body: JSON.stringify({
data: data
}),
headers: {
'Content-Type': 'application/json',
}
}).then((res) => {
console.log("wait for whole req");
return res.json();
}).then((resData) => {
console.log(resData);
console.log("req send successfully");
// note = null;
}).catch((error) => {
// note = null;
console.log(error.message);
// alert(error.message);
});
Back-End:
app.post("/post", function(req, res) {
const data = req.body.data;
dataList.push(data);
res.status(200).json({
status: "uploaded"
});
});
Here, data is one array that stores data taken from the user.

You can limit concurrent requests by a flag
var data = null,
isLoading = false, // perhaps you need to make this persistent depending on your overall architecture
if (!isLoading)
{
data = prompt("Enter your data here");
}
if (data !== null || data !== ''){
isLoading = true;
fetch('http://localhost:3000/post', {
method: 'POST',
body: JSON.stringify({
data: data
}),
headers: {
'Content-Type': 'application/json',
}
}).then((res) => {
console.log("wait for whole req");
return res.json();
}).then((resData) => {
console.log(resData);
console.log("req send successfully");
isLoading = false
// note = null;
}).catch((error) => {
// note = null;
console.log(error.message);
isLoading = false
// alert(error.message);
});

Related

passing binary data to rest-api

I want to upload a thumbnail to viemo api , and based on Vimeo doc, I must include the thumbnail file as binary data in the request body, I have to upload the thumbnail from the client side "fontend" and will send the request from the rest-api "backend" the problem is my rest-api can't receive the binary data, properly because I'm using express.js, is there any way to handle the binary data in the backend.
the steps as following:
client side sent thumbnail data => backend receive the data through the request body and send it to => endpoint
client side request
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('selectedFile', new Blob([selectedFile], { type: 'application/json' }));
formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.post(`${backendPostPath}/thumbnail-upload`, formData, {
headers,
})
.then((response) => {
applyThumbnial();
console.log(`${uploadLink}link for upload`);
});
} catch (error) {
console.log(error);
}
};
backend request can't receive the body request of frontend post as binary data,
const ThumbnailUpload = async (req, res) => {
const { uploadLink } = req.body;
const { selectedFile } = req.body;
console.log(uploadLink);
const clientServerOptions = {
uri: `${uploadLink}`,
encoding: null,
body: JSON.stringify({
name: uploadLink,
file: selectedFile,
}),
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions, function (error, response) {
if (error) {
res.send(error);
} else {
const body = JSON.parse(response.body);
res.send(body);
}
});
};
is there any way to make the backend request body fetch the binary data, as I getting the data as "undefined"
Sorry for late update, I solved this issue by using the same put request form the client side, as the put request don't require Vimeo access token, so you can use the same put request i mentioned above, and remove authentication from the header, like following
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('selectedFile', new Blob([selectedFile], { type: 'image/jpg, image/png' }));
// formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'image/jpg, image/png',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.put(`${uploadLink}`, formData, {
headers,
})
.then((response) => {
console.log(`${uploadLink}link for upload`);
});
} catch (error) {
console.log(error);
}
};

Trying to dynamically set .find() parameters from client input - mongodb:Atlas

I am trying to use data from the client, which they would type into an input box. The idea is to use this for finding in my database to pull the data with the same username. on my Mongo DB:Atlas collection.
So its to use it like this to get the names from the database, .find({"username": request.body})
However, I keep getting the error "CastError: Cast to string failed for value "{ username: '' }" (type Object) at path "username" for model "Db1" on my terminal.
But when I try to hard code it onto the .find({"username": "name"), it works fine. Does anyone have any ideas?
**Javascript app**
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
};
```
-----------------------------------------------------
**Node Server**
app.post('/database', (request,response) => {
const info = request.body;
postModel.find({"username": info}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});
----------------------------------------------
***client side DB***
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
Actually, you're passing the object {username : "value"} to the find method. You need to pass the string.
app.post('/database', (request,response) => {
const info = request.body; // object {username : "value"}
const username = info.username; // the string to search by username
postModel.find({"username": username}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});

How to a read a string value after post response with fetch api

I am trying to get the response and be able to read the value of the post it returns either as null or has data to verify the post before moving on to the next section, I am using the fetch api method I got the response and got it working with the form but I cant get the javascript to read if the response is null or not but got it on the console. Here is the code.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Origin", "*");
var acct = JSON.stringify({"acct":account});
var requestOptions = {
method: 'POST',
mode: 'cors',
headers: myHeaders,
body: acct,
//credentials: "include",
redirect: 'follow'
};
const doAjax = async () => {
const response = await fetch('http://myrestapi', requestOptions);
if (response.ok) {
const aVal = await response.text();
return Promise.resolve(aVal);
//return aVal;
}
else
{
return Promise.reject('*** PHP file not found');
}
}
function postData() {
if(response => response == null){
console.log("I am Null ");
}
else
{
console.log("I am ALIIIIIIVE ");
}
}
doAjax()
.then(response => console.log(response))
.finally(response => postData())
.catch(error => console.log('error', error + account));
You probably want to pass the response to postData like this:
function postData(response) {
if(response === null) {
console.log("I am Null ");
} else {
console.log("I am ALIIIIIIVE ");
}
}
doAjax()
.then(response => postData(response))
.catch(error => console.log('error', error + account));

Unable to get fetch response on react native app

I am stuck on one of the mysterious issue. The problem goes like this:
What I Do??
Simply do login api call and if login success then I have to fetch amount of data from 5-6 api calls and store them in local database (Realm). Here is my code.
login(email, password) {
this.toggleLoadingFunction(true);
fetch(LoginURL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
request_from: 'mobile'
}),
})
.then(async res => {
if (res.ok) {
let data = await res.json();
global.user = data['user']
global.token = data['token']
getAllMasterDataAndSaveInRealm().then(() => {
this.toggleLoadingFunction(false);
global.storage.save({ key: 'LoggedInData', data: data });
this.props.navigation.navigate('Project', data);
}).catch(() => {
this.toggleLoadingFunction(false);
Alert.alert("Master Data Failed !!!");
})
} else {
this.toggleLoadingFunction(false);
let data = await res.json();
Alert.alert("Login Failed!!!", data.message)
}
})
.catch(error => {
this.toggleLoadingFunction(false);
Alert.alert("Network Error. Please try again.")
})
Here getAllMasterDataAndSaveInRealm() is lies on helper function which calls 5-6 apis and response back if all work is done. Here is how it looks like:
export const getAllMasterDataAndSaveInRealm = () => {
const token = global.token;
return new Promise.all([
getMaterials(token),
getEquipments(token),
getObjective(token),
getCategories(token),
getNcData(token),
getPlans(token)]
);
}
Each function inside getAllMasterDataAndSaveInRealm() returns Promise after successfully stored data in local realm db. Here is one of the above function.
export const getActivityPlan = (token) => {
return new Promise((resolve, reject) => {
return fetch(FetchActivityPlanDataURL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access_token': `${token}`
}
}).then((response) => {
console.log("Activity Plans Api response", response);
return response.json()
})
.then((responseJson) => {
const { data } = responseJson
console.warn("Activity Plans Api", data);
global.realm.write(() => {
for (var item of data) {
item.id = item.id ? item.id : 0;
item.activity_id = item.activity_id ? item.activity_id.toString() : "";
item.activity_name = item.activity_name ? item.activity_name.toString() : "";
item.activity_cost = item.activity_cost ? item.activity_cost.toString() : "";
item.project_id = item.project_id ? item.project_id : 0;
global.realm.create("ActivityPlan", item, true);
}
})
resolve(data);
})
.catch((error) => {
reject(`Activity Plan Failed ${error}`)
});
})
}
All remaining functions are same as above ( what they do is simply fetch data from api and store it in realm and resolve or reject)
What I Expect:
getAllMasterDataAndSaveInRealm() function Just store all the required data in db and let me know all done and then navigate to the another screen, as Login and fetching data is done.
Problem:
When I do run the app and process for login, Sometimes it works fine but most of the time App stuck on showing loader since some of the api call among 6 api from above do not get response from the request ( I do log the response) on wifi. But when I use mobile data and VPN it always works.
When I log request on server console, response is sent with code 200, but app is unable to get response for the request.
I am new on react native. I do lots of searches over internet but unable to find the solution. I don't have any idea whats going wrong with the code. Please help me out.
Project Configurations:
"react": "16.8.6",
"react-native": "0.60.4",
"realm": "^2.29.2",
Node version: v9.0.0

coverting javascript to python

I have a yale smart alarm and come across the the below javascript that allows you to access the alarm to get the status and set it. I'm wanting to use this in my home assistant set to which uses python.
const fetch = require('node-fetch');
const setCookie = require('set-cookie-parser');
const urls = {
login: 'https://www.yalehomesystem.co.uk/homeportal/api/login/check_login',
getStatus: 'https://www.yalehomesystem.co.uk/homeportal/api/panel/get_panel_mode',
setStatus: 'https://www.yalehomesystem.co.uk/homeportal/api/panel/set_panel_mode?area=1&mode=',
};
function getSessionCookie(username, password) {
let sessionCookie = null;
return fetch(urls.login, {
method: 'POST',
body: `id=${encodeURIComponent(username)}&password=${password}&rememberme=on&notify_id=&reg_id=Name`,
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
},
})
.then((res) => {
sessionCookie = res.headers._headers['set-cookie'];
return res.json();
}).then(json => {
if (json.result === '0') {
return Promise.reject('Incorrect account details');
}
else {
return sessionCookie[0];
}
})
}
function getStatus(sessionCookie) {
return fetch(urls.getStatus, {
method: 'POST',
headers: {
'Cookie': sessionCookie,
},
}).then(res => res.text()).then(textResponse => {
// When initially writing this code I found if cookie payload
// was invalid I got this text response so I added this code to
// handle this, shouldn't happen but good to have an error message
// for this use case
if (textResponse === 'Disallowed Key Characters.') {
return Promise.reject('Invalid request');
}
else {
try {
// Hopefully if we got to this point we can parse the json
const json = JSON.parse(textResponse);
if (json.result === '0') {
return Promise.reject('Unable to get status');
}
else {
return json;
}
} catch (error) {
// If you get this error message I likely have not handled
// a error state that I wasnt aware of
return Promise.reject('Unable to parse response');
}
}
});
}
function setStatus (sessionCookie, mode) {
return new Promise((resolve, reject) => {
if (!sessionCookie || sessionCookie.length === 0) {
reject('Please call getSessionCookie to get your session cookie first');
}
if (mode !== 'arm' && mode !== 'home' && mode !== 'disarm') {
reject('Invalid mode passed to setStatus');
}
resolve(fetch(`${urls.setStatus}${mode}`, {
method: 'POST',
headers: {
'Cookie': sessionCookie,
},
}));
});
}
module.exports = {
getSessionCookie,
getStatus,
setStatus,
}
i'm every new to coding but was able to piece the below together to return the current status of my alarm. the problem is I'm unable to get it to work. based on the above code could someone please tell me what I'm missing, or if I'm going down the wrong rabbit hole....
import requests
import webbrowser
url = “https://www.yalehomesystem.co.uk/homeportal/api/login/check_login”
payload = {‘username’: ‘email#domaim.com’, ‘password’: ‘mypass’}
with requests.session() as s:
# fetch the login page
s.get(url, data=payload)
url1='https://www.yalehomesystem.co.uk/homeportal/api/panel/get_panel_mode'
# post to the login form
r = s.post(url1, data=payload)
print(r.text)
To add more contexts I'm getting the following error
{"result":"0","message":"system.permission_denied","code":"999"}

Categories

Resources