i deployed an app to heroku which has a fucntion that counts clicks of elements and add it to JSON file
my main.js is like this
var fs = require('fs');
var file = fs.readFileSync('count.json');
var Words = JSON.parse(file);
const express = require('express');
const app = express();
app.listen(process.env.PORT || 3000, () => console.log('we are listeining'));
app.use(express.static('public'));
app.use(express.json({ limit : '1mb' }));
app.get('/add/:word', addWord);
function addWord(request, response) {
var data = request.params;
var word = data.word;
var reply;
var found = false;
for (i = 0; i < Words.length; i++){
if (Words[i].type == word){
Words[i].count++;
found = true;
break;
}
}
if (!found) {
Words.push({"type": word , "count": 1});
}
var x = JSON.stringify(Words, null, 2);
fs.writeFile('count.json', x, finished);
function finished(){
console.log('Yay')
}
/*
console.log(Words[word]); */
/* response.send(reply); */
}
and the script file is like this
all.forEach(element => {
element.addEventListener('click', function(e){
elemid = e.target.id;
elemclass = e.target.className;
let div = document.createElement('div');
div.id = elemid + "_overlay";
div.className = "overlay";
document.body.appendChild(div);
div.style.display = "block";
fetch(elemid+'.txt')
.then(response => response.text())
.then((data) => {
div.innerHTML = data;
}).then(fetch("/add/"+elemid)
.then(response => {
return response.json();
}).then(function(data){
console.log(data[0].count);
})
.then(fetch('js/cases.json')
.then(response => response.json())
.then((data) =>{
for (i = 0; i < data.length; i++){
if (elemid == data[i].case){
let a = document.createElement('a');
a.id = data[i].id;
a.innerText = data[i].case
div.appendChild(a);
}
}
console.log(data[0].id);
})
)
)
}, false)
})
locally it writes the JSON of of count perfectly but when deployed it on heroku changes doesn't take effect and there is no error appears in the console.
Related
i have a ajax chat with laravel and every thing going okay when i open the chat but when i get new message the all old message repeated too , so i write a statement to prevent that because the normal is when i enter the page the chat load all old messages and when come any new message should append it not append the all old messages
if(chat_history.childElementCount !== data.messages.length)
but when i send any new message the statement will be false so what's solution here please
function getMessages(route,theTeacher) {
let chat_history = document.querySelector('#chat_history');
let options = {
method: 'GET',
headers: {
'Content-Type':
'application/json;charset=utf-8',
'X-CSRF-TOKEN':
document.head.querySelector("[name=csrf-token]").content
},
}
fetchRes = fetch(`${route}/${theTeacher}`, options);
fetchRes.then((response) => {
return response.json()
})
.then((data) => {
if(chat_history.childElementCount !== data.messages.length)
{
for (let c in data.messages) {
if(data.messages[c].sender.indexOf('admin') > -1) {
let liTwo = document.createElement("li");
let message_data = document.createElement("div");
let message_data_span = document.createElement("span");
let my_messages = document.createElement("div");
liTwo.classList.add('clearfix');
message_data.classList.add('message-data', 'text-right')
my_messages.classList.add('message', 'my-message');
message_data_span.classList.add('message-data-time');
message_data_span.innerText = data.messages[c].created_at;
message_data.innerHTML = message_data_span.outerHTML;
my_messages.innerText = data.messages[c].message;
liTwo.appendChild(message_data);
liTwo.appendChild(my_messages);
chat_history.append(liTwo);
// message_data_img.src = d
}
if (data.messages[c].sender.indexOf('teacher') > -1) {
let li = document.createElement("li");
let message_data = document.createElement("div");
let message_data_span = document.createElement("span");
let message_data_img = document.createElement("img");
let other_message = document.createElement("div");
li.classList.add('clearfix');
message_data.classList.add('message-data', 'text-right')
other_message.classList.add('message','other-message', 'float-right')
message_data_span.classList.add('message-data-time');
message_data_span.innerText = data.messages[c].created_at;
message_data_img.src = 'http://127.0.0.1/twaqah-project/twaqah/public/storage/' + data.teacher.avatar;
message_data.innerHTML = message_data_span.outerHTML + message_data_img.outerHTML;
other_message.innerText = data.messages[c].message;
li.appendChild(message_data);
li.appendChild(other_message);
chat_history.append(li);
// message_data_img.src = d
}
}
}
});
}
the blade code
setInterval(function() {
getMessages('{{route('chat.teacher-get-messages')}}',{{request()->teacher}});
}, 3000);
My shoutbox project works just find when I run it on localhost, "npm start" for the "server.js" which and I use Live Server to open "client.js" in browser. In localhost everything runs smoothly, when server starts, I can open it in browser. API request are sent good an received data parsed, display and also saved to MongoDB.
But when I deployed it onto Netlify, the following looping errors appear in the console:
"Failed to load resource: the server responded with a status of 404 (Not Found)" "polling-xhr.js:202 GET https://shoutboxbymurad.netlify.app/socket.io/?EIO=4&transport=polling&t=O1xOrfM 404 (Not "
Client.js is:
// Variables:
const socket = io('localhost:3000'); //localhost:3000
const messages = document.getElementById('messages'); // Messages field
const msgForm = document.getElementById('msgForm'); // Message form
const msgInput = document.getElementById('msgInput'); // Message input field
const userNameInput = document.getElementById('username'); // Username input field
const usrsList = document.getElementById('users-list');
var userName = '';
var onlineUsers = [];
var clientIp = '';
var clientRegion = '';
// Functions:
socket.on('welcome-message', (msg) => {
const html = `<div style="font-weight: bold; color:rgb(53, 247, 111);">${msg}</div>`;
messages.innerHTML += html;
});
socket.on('message', (msg, usr) => {
appendMessage(msg, usr);
});
const appendMessage = (message, user) => {
handleURL(message, user);
};
const handleURL = (message, user) => {
message = message.split(' ');
for (let i = 0; i < message.length; i++) {
if (message[i].includes('http' || 'https')) {
message[i] =
`${message[i]}`;
}
}
message = message.join(' ');
const html = `<div style="font-weight: bold; text-transform: uppercase; color: black; font-size: 1rem">${user}:<span style='text-transform: none;'>${message}</span></div>`;
messages.innerHTML += html;
};
socket.on('get-messages', (data) => {
let arr = [];
let limitMessages = 9; // Number of messages new connect users will get (9 by default, change if want otherwise)
for (let i = 0; i < data.length; i++) {
arr.push(JSON.parse(data[i]));
}
if (arr.length > limitMessages) {
// if number of messages in array is more than 9, then get the last 9 messages
arr = arr.slice(arr.length - limitMessages);
}
arr.map((msg) => {
const html = `<li style="color:blue;font-weight:bold; font-size: 1rem">${msg.name}:<span style="color:blue">${msg.message}<span></li>`;
messages.innerHTML += html;
});
});
socket.on('get-online-users-list', (usersData) => {
appendToOnlineBox(usersData);
});
socket.on('update-online-users-list', (data) => {
// alert(data);
removeFromOnlineBox(data);
});
const removeFromOnlineBox = (data) => {
usrsList.innerHTML = '';
let arr = [];
for (let i = 0; i < data.length; i++) {
arr.push(JSON.parse(data[i]));
}
onlineUsers.length = 0;
for (let i = 0; i < arr.length; i++) {
if (!onlineUsers.includes(arr[i].name)) {
onlineUsers.push(arr[i].name, arr[i].ip, arr[i].clientRegion);
}
}
onlineUsers.map((user) => {
let onlineUser = `<li style="border: 4px solid blue; padding:0px; margin:0"><div style="border: 2px solid green; padding:0">${user}</div></li>`;
usrsList.innerHTML += onlineUser;
});
};
const appendToOnlineBox = (data) => {
usrsList.innerHTML = '';
let arr = [];
for (let i = 0; i < data.length; i++) {
arr.push(JSON.parse(data[i]));
}
for (let i = 0; i < arr.length; i++) {
if (!onlineUsers.includes(arr[i].name)) {
onlineUsers.push(arr[i].name, arr[i].ip, arr[i].clientRegion);
}
}
onlineUsers.map((user) => {
let onlineUser = `<li style="border: 4px solid blue; padding:0px; margin:0"><div style="border: 2px solid green; padding:0">${user}</div></li>`;
usrsList.innerHTML += onlineUser;
});
};
msgForm.addEventListener('submit', (e) => {
e.preventDefault();
socket.emit(
'chatmessage',
userName,
socket.id,
msgForm.msg.value,
clientIp,
clientRegion
);
msgForm.msg.value = '';
});
const checkUserName = () => {
msgInput.disabled = true;
userNameInput.addEventListener('change', () => {
if (userNameInput.value !== '') {
msgInput.disabled = false;
userNameInput.disabled = true;
userName = userNameInput.value;
}
});
};
// GET CLIENT INFO:
const getClientIpAndRegion = () => {
fetch('http://www.geoplugin.net/json.gp')
.then((res) => res.json())
.then((data) => {
clientIp = data.geoplugin_request;
clientRegion = data.geoplugin_countryName;
});
};
// Function calls:
checkUserName(); // Check if a user inserted a useraname
getClientIpAndRegion(); // Get clients' IP address and client Geolocation (region)
Server.js is:
const mongoose = require('mongoose'); // get mongoose
const mongoDB =
'....';
mongoose
.connect(mongoDB, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => {
console.log('Conncected to MongoDB...');
})
.catch((err) => {
console.log(err);
});
const UsrData = require('./Models/UserDataSchema');
var io = require('socket.io')(3000, {
cors: {
origin: '*',
},
});
var user = new Object(); // Socket client user object
var userData = []; // objects array to store information on connected user's name, socket.id and message : Array of object strings
var data; // variable to hold UserData Schema
io.on('connection', (socket) => {
socket.emit('welcome-message', 'WELCOME TO THE SHOUTBOX'); // Emit welcome message to new user
io.emit('get-online-users-list', userData); // Emit online users list to new user
socket.emit('get-messages', userData); // Emit all previous messages from users to new user
socket.on('disconnect', () => {
//handle user disconnect
let arr = [];
for (let i = 0; i < userData.length; i++) {
arr.push(JSON.parse(userData[i]));
}
arr = arr.filter((user) => user.socketId !== socket.id);
userData.length = 0;
for (let i = 0; i < arr.length; i++) {
userData.push(JSON.stringify(arr[i]));
}
io.emit('update-online-users-list', userData);
});
socket.on(
'chatmessage',
(username, socketid, formValue, clientIp, clientRegion) => {
if (username !== '' && formValue !== '') {
user.name = username;
user.socketId = socketid;
user.message = formValue;
user.ip = clientIp;
user.clientRegion = clientRegion;
io.emit('message', user.message, user.name);
userData.push(JSON.stringify(user));
data = new UsrData({ data: userData }); //===> Create a new NoSQL document with userData
data.save(); // ===> Save the document to MongoDb
io.emit('get-online-users-list', userData);
}
}
);
});
I tried to send my variable back from foreground.js to background.js by using an unchanged variable, and it works. Now I can't send some data that I use my AddEventListener syntax to store the data into the variable to call its back to background.js here are my code on foreground.js
foreground.js
console.log("foreground.js injected");
var pswdBtns = [];
let hrefLists = [];
var data = {};
var i;
function readUUID(){
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
return uid;
}
async function passwordProtected(pointerList){
const date = new Date();
const uid = readUUID();
alert("You are in dangerous on \'"+ pointerList.title + "\' row = " + pointerList.id.slice(20));
data = {
"Webtitle": pointerList.href,
"Title": pointerList.title,
"Time": date.toString(),
"UUID": uid
}
console.log("foreground = ", data);
return data;
}
console.log("Start loop")
//This function made for collect each id in passwordShowPasswordButton
for(i = 0; i<=pswdBtns.length; i++){
if(document.querySelector("#passwordShowPasswordButton_"+ i) == null){
console.log("This is your limit!!");
}
else{
hrefLists[i] = document.querySelector("#passwordWebsitelink_"+ i);
pswdBtns[i] = document.querySelector("#passwordShowPasswordButton_"+ i);;
data = pswdBtns[i].addEventListener('click', passwordProtected.bind(pswdBtns[i], hrefLists[i]));
console.log(hrefLists[i].title); /* Title VARCHAR(30) */
console.log(hrefLists[i].href); /* Website VARCHAR(50) */
}
}
console.log("End");
and these are my code on background.js
background.js
const edgePswd = "edge://settings/passwords";
const settingPage = "edge://settings/";
chrome.tabs.onActivated.addListener(async (tab) => {
await chrome.tabs.get(tab.tabId, (current_tab_info) => {
var pswdPageChecked = 1;
while(pswdPageChecked < 2) {
if (edgePswd == current_tab_info.url) {
chrome.tabs.executeScript(null, { file: "/extension/foreground.js" }, (data) => {
console.log("Coming to foreground");
console.log(data);
});
pswdPageChecked++;
}
}
});
});
It would be a pleasure if someone can figure this.
so im getting my data from Darksky api, i have elements generated with loops, and i update the text content of those via loop of the api data array. whenever i search, everthing else static changes values, not the one inside the loop
function search(ele) {
if(event.key === 'Enter') {
var url3 = 'https://geocode.xyz/' + ele.value +'?json=1' //this is where i convert the long,lat to city name
fetch(url3)
.then(z => z.json())
.then(z => {
locres = (z.latt+','+z.longt)
render()
renderLoop()
})
}
}
function renderLoop(){
var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
var url1 = 'https://api.darksky.net/forecast/c34e122a56ae30a3090687878bce72c3/' + locres + '?units=auto' //i have to use proxy because of CORS
fetch(proxyUrl + url1)
.then(x => x.json())
.then(x => {
var skycons = new Skycons({"color": "white"});
skycons.set("icon0", Skycons = x.currently.icon);
skycons.play();
console.log(x.daily.data)
for(i=0;i<8;i++){
console.log(x.daily.data[i].time)
console.log(x.daily.data[i].summary)
const divs = document.createElement('div')
divs.className = ('week-day-container')
const divsholdr = document.querySelector('.week-stage')
const canv = document.createElement('canvas')
canv.id = ('icons'+(i+1))
canv.height = 100
canv.width = 70
divs.appendChild(canv)
divsholdr.appendChild(divs)
const dates = document.createElement('p')
dates.textContent = x.daily.data[i].time
divs.appendChild(dates)
const temp = document.createElement('p')
temp.textContent = 'High: '+ x.daily.data[i].temperatureHigh + 'Low: ' + x.daily.data[i].temperatureLow
divs.appendChild(temp)
const summ = document.createElement('p')
summ.textContent = x.daily.data[i].summary
divs.appendChild(summ)
}
for(y=0;y<8;y++){
skycons.set('icons'+(y+1), Skycons = x.daily.data[y].icon)
}
})
}
How can I handle request fails in this example of axios.all requests. I.e. if all servers are responde with JSON all is okay and I have JSON file at end of a cycle. But if one of this servers not responde with JSON or not responde at all I do have nothing in "/data.json" file, even all other servers are working perfectly. How can I catch a server fail and skip it?
var fs = require("fs");
var axios = require('axios');
var util = require('util');
var round = 0;
var tmp = {};
var streem = fs.createWriteStream(__dirname + '/data.json', {flags : 'w'});
toFile = function(d) { //
streem.write(util.format(d));
};
start();
setInterval(start, 27000);
function start(){
streem = fs.createWriteStream(__dirname + '/data.json', {flags : 'w'});
monitor();
}
function monitor(){
axios.all([
axios.get('server1:api'),
axios.get('server2:api'),
axios.get('server3:api'),
axios.get('server4:api'),
]).then(axios.spread((response1, response2, response3, response4) => {
tmp.servers = {};
tmp.servers.server1 = {};
tmp.servers.server1 = response1.data;
tmp.servers.server2 = {};
tmp.servers.server2 = response2.data;
tmp.servers.server3 = {};
tmp.servers.server3 = response3.data;
tmp.servers.server4 = {};
tmp.servers.server4 = response4.data;
toFile(JSON.stringify(tmp));
round++;
streem.end();
streem.on('finish', () => {
console.error('Round: ' + round);
});
})).catch(error => {
console.log(error);
});
}
The most standard way to approach this would be a recursive function like below.
let promises = [
axios.get('server1:api'),
axios.get('server2:api'),
axios.get('server3:api'),
axios.get('server4:api'),
];
async function monitor() {
const responses = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments))[0];
const nextPromise = promises.shift();
if (nextPromise) {
try {
const response = await getSentenceFragment(offset);
responses.push(response);
}
catch (error) {
responses.push({});
}
return responses.concat(await monitor(responses));
} else {
return responses;
}
}
monitor([]).then(([response1, response2, response3, response4]) => {
tmp.servers = {};
tmp.servers.server1 = {};
tmp.servers.server1 = response1.data;
tmp.servers.server2 = {};
tmp.servers.server2 = response2.data;
tmp.servers.server3 = {};
tmp.servers.server3 = response3.data;
tmp.servers.server4 = {};
tmp.servers.server4 = response4.data;
toFile(JSON.stringify(tmp));
round++;
streem.end();
streem.on('finish', () => {
console.error('Round: ' + round);
});
});