node js post request - node.js

Success localhost response
Cannot GET /u/coupons at server
Frontend script for post
<script>
var count = document.getElementById("count");
var len = document.getElementById("length");
var pattern = document.getElementById("pattern");
document.getElementById('coupons-button').onclick = function()
{
if(count.value!=="" && len.value!=="")
{
const genReq = new XMLHttpRequest();
let url = `count=${encodeURI(count.value)}&` +
`len=${encodeURI(len.value)}&` +
`pattern=${encodeURI(pattern.value)}`;
genReq.open('POST',`/u/coupons?${url}`,true);
genReq.send();
genReq.onreadystatechange = e => {
if(genReq.readyState === 4 && genReq.status === 200){
let gen = JSON.parse(genReq.response);
if (gen.state === "SUCCESS")
{
var coupons = gen.coupons;
for(var i=0;i<coupons.length;i++)
{
var div = document.createElement('div');
var text = document.createTextNode(coupons[i]);
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
} else {
var div = document.createElement('div');
var text = document.createTextNode("FAIL TO GENERATE");
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
}
}
}
}
Server script
admin.post( '/u/coupons' ,(req,res)=>{
let params = getParameters(req);
CouponWorker.generateCoupons({
"len":decodeURI(params.len),
"count":decodeURI(params.count),
"pattern":decodeURI(params.pattern)
}).then((_res) =>{
console.log(_res)
if(_res.success === true)
{
res.status(200).json({
"state":"SUCCESS",
"coupons":_res.coupons
});
}
else{
res.status(200).json({"state" : "FAILED"});
}
});
});
CouponWorker
const firebase = require('./Database');
const voucher_codes = require('voucher-code-generator');
exports.generateCoupons = function(params)
{
var len = params.len;
var count = params.count;
var pattern = params.pattern;
//pattern = pattern.replace(/1/g,'#');
const cpn_db = firebase.firebase.database();
var coupons;
return new Promise((resolve,reject)=>{
coupons = voucher_codes.generate({
length:len,
count:count,
prefix:"AMP-",
pattern: '####-####',
charset:"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
});
if(coupons!==null)
{
for(var i =0;i<count;i++)
{
cpn_db.ref('coupons/cid-'+coupons[i]).set({
"addedOn": getDateTime(),
"code" : coupons[i],
"amount" : 20,
"expireDate" : null,
"isActive" : true,
"isDeleted":false
});
}
resolve({
"success":true,
"coupons":coupons
});
}
else
{
resolve({
"success":false
});
}
});
}
Above given snaps shows the same code running on localhost and server,
localhost working fine,giving output and saving data to firbase while server response 404 not found resource.
I can not find the reason of this error.I tried url req on postman and responses are the same as above

Related

TinyMCE text is not being saved completely

I am making an online text editor that saves the content to a database while typing and returns it to the textarea, using TinyMCE, React as frontend and Node+Express as backend
Sometimes it doesn't send the whole content to the database and i have to switch tabs and return to the editor, typing a space character so it sends the resting content
I tried using "onKeyUp", "onKeyDown" but the characters got imediatly deleted after trying to type, currently I'm using "onEditorChange" to activate the function.
Here's my code:
function App() {
const editorRef = useRef();
const { route } = useParams();
const url = "https://API/" + route;
const { httpConfig } = useFetch(url);
const [notas, setNotas] = useState("");
const [rota, setRota] = useState("");
const [init, setInit] = useState(false);
useEffect(() => {
(async () => {
let res = "";
let data = "";
if (init) {
const notinhas = {
content: notas,
rota: route,
};
httpConfig(notinhas, "PATCH");
} else {
res = await fetch(url);
data = await res.json();
if (data === null) {
const notinhas2 = {
content: "",
rota: route,
};
httpConfig(notinhas2, "POST");
} else {
setNotas(data.content);
}
}
})();
}, [notas, init]);
function onClickHandler() {
setNotas(editorRef.current.getContent());
}
return (
<div>
<Editor
onEditorChange={onClickHandler}
onInit={ (evt, editor) =>
{editorRef.current = editor;
editor.selection.select(editor.getBody(), true);
editor.selection.collapse(false);
setInit(true);
}}
init={{
plugins: "...",
toolbar: "...",
setup: function(editor) {
editor.on('keydown', function() {
var currNode = editor.selection.getNode();
var currText = currNode.textContent;
if (currNode.nodeName.toLowerCase() != 'p' || currText.length < 1) return;
var pCount = editor.dom.doc.querySelectorAll('p').length;
setTimeout(function() {
var newNode = editor.selection.getNode();
var newText = newNode.textContent;
var newPCount = editor.dom.doc.querySelectorAll('p').length;
if (pCount + 1 == newPCount && currText == newText) {
var nextNode = newNode.nextElementSibling;
var nextNodeText = nextNode.textContent;
if (nextNode.nodeName.toLowerCase() != 'p' || nextNodeText.length > 1) return;
nextNode.innerHtml = '<br>';
editor.selection.setCursorLocation(nextNode, 0);
}
}, 80);
});
editor.on('init', function()
{
this.getDoc().body.style.fontSize = '12pt';
this.getDoc().body.style.fontFamily = 'monospace';
});
}}}
value={notas}
/>
</div>
);
}
export default App;
Could someone help me in this?

google cloud function error DEADLINE EXCEEDED

I'm trying to write a simple pub/sub triggered cloud function to update my Firestore collection of stocks.I'm getting a bunch of weird error messages with one prominent of Error: 4 DEADLINE_EXCEEDED: Deadline exceeded. Whats even more strange that some stocks gets updated correctly while others don't. Im new to Javascript/Typescript so obviously I have some misunderstanding about how to return promises in this case here. The idea here is very simple loop through each ticker in the collection make a request to updated data then update existing document data and save it
export const updateChart = functions.pubsub.schedule('35 16 * * 1-5').timeZone('America/New_York').onRun(async(_context) => {
const key = functions.config().services.key as string
const db = admin.firestore()
const charts5DRef = db.collection("charts5D")
var needsUpdate : boolean = true
// I cut off some unrelated code for brevity sake
if (needsUpdate){
const snapshot = await charts5DRef.get()
var path = ``
const timestamp = Date.now() / 1000
return snapshot.forEach(async function(document){ // this could contain 100's of stock tickers
const ticker = document.id
const docData = document.data()
var labels = docData.labels as [string]
var marketNotional = docData.marketNotional as [number]
var marketTrades = docData.marketNumberOfTrades as [number]
var dates = docData.dates as [string]
var closings = docData.close as [number]
var volume = docData.marketVolume as [number]
path = `apiUrl to get data`
const options = {
method : 'GET',
uri : path,
resolveWithFullResponse : true,
}
await req(options).then(async(response)=>{
if(response.statusCode === 200){
const resultData = JSON.parse(response.body)
const updatedPrices = resultData as [IntradayPrice]
updatedPrices.forEach(function(value){
if(value.close !== undefined){
closings.splice(0,1)
marketTrades.splice(0,1)
marketNotional.splice(0,1)
labels.splice(0,1)
dates.splice(0,1)
volume.splice(0,1)
closings.push(value.close)
dates.push(value.date)
if(value.label !== undefined){ labels.push(value.label) } else { labels.push("") }
if(value.marketNotional !== undefined) { marketNotional.push(value.marketNotional) } else { marketNotional.push(0) }
if(value.marketNumberOfTrades !== undefined) { marketTrades.push(value.marketNumberOfTrades) } else { marketTrades.push(0) }
if(value.marketVolume !== undefined) { volume.push(value.marketVolume) } else { volume.push(0) }
}
})
await charts5DRef.doc(ticker).set({lastUpdate : timestamp,close : closings, labels : labels, marketVolume : volume,marketNumberOfTrades : marketTrades, marketNotional : marketNotional, dates : dates}).then(()=>{
console.log(`Updated ${ticker} 5Dchart successfully`)
}).catch((error)=>{
console.log(error)
})
}
}).catch((error)=>{
console.log(error)
})
})
}else{
console.log("Markets closed")
return
}
})
ok so this solved the errors
export const updateChart = functions.pubsub.schedule('35 16 * * 1-5').timeZone('America/New_York').onRun(async(_context) => {
const key = functions.config().services.key as string
const db = admin.firestore()
const charts5DRef = db.collection("charts5D")
var needsUpdate : boolean = false
if (needsUpdate){
const snapshot = await charts5DRef.get()
var path = ``
const timestamp = Date.now() / 1000
const promises : bird<void>[] = []
snapshot.forEach(async function(document){
const ticker = document.id
const docData = document.data()
var labels = docData.labels as [string]
var marketNotional = docData.marketNotional as [number]
var marketTrades = docData.marketNumberOfTrades as [number]
var dates = docData.dates as [string]
var closings = docData.close as [number]
var volume = docData.marketVolume as [number]
path = `https://cloud.iexapis.com/stable/stock/${ticker}/intraday-prices?token=${key}&chartInterval=10`
const options = {
method : 'GET',
uri : path,
resolveWithFullResponse : true,
}
const promise = req(options).then(async(response)=>{
if(response.statusCode === 200){
const resultData = JSON.parse(response.body)
const updatedPrices = resultData as [IntradayPrice]
updatedPrices.forEach(function(value){
if(value.close !== undefined){
closings.splice(0,1)
marketTrades.splice(0,1)
marketNotional.splice(0,1)
labels.splice(0,1)
dates.splice(0,1)
volume.splice(0,1)
closings.push(value.close)
dates.push(value.date)
if(value.label !== undefined){ labels.push(value.label) } else { labels.push("") }
if(value.marketNotional !== undefined) { marketNotional.push(value.marketNotional) } else { marketNotional.push(0) }
if(value.marketNumberOfTrades !== undefined) { marketTrades.push(value.marketNumberOfTrades) } else { marketTrades.push(0) }
if(value.marketVolume !== undefined) { volume.push(value.marketVolume) } else { volume.push(0) }
}
})
await charts5DRef.doc(ticker).set({lastUpdate : timestamp,close : closings, labels : labels, marketVolume : volume,marketNumberOfTrades : marketTrades, marketNotional : marketNotional, dates : dates}).then(()=>{
console.log(`Updated ${ticker} 5Dchart successfully`)
}).catch((error)=>{
console.log(error)
})
}
}).catch((error)=>{
console.log(error)
})
promises.push(promise)
})
return Promise.all(promises).then(()=>{
console.log("All good")
}).catch((error)=>{
console.log(error)
})
}else{
console.log("Markets closed")
return
}
})

How can I post a GIF image to twitter using Twit library?

I am trying to build a small bot that posts random GIFs to twitter based on a hard-coded category (for now).
I am using Twit library for making posts to twitter using the Twitter API. How can I post a GIF to twitter?
Here's the code :
var twit = require('twit');
var config = require('./config');
var request = require('request');
var fs = require('fs');
var path = require('path');
const GIPHY_API_KEY = 'API-KEY';
const GIPHY_API_URL = 'http://api.giphy.com/v1/gifs/random? api_key='+GIPHY_API_KEY+'&tag=study';
var T = new twit(config);
getAndPostGifImg();
function getAndPostGifImg() {
request(GIPHY_API_URL,function (error,response,body) {
var resp = JSON.parse(body);
var img_url = resp.data.image_url;
console.log(img_url);
// post the image to twitter
postImg(img_url);
});
function postImg(img_url) {
request(img_url).pipe(fs.createWriteStream('images/imgpost.gif'));
var filename = path.join(__dirname,'/images/','imgpost.gif');
var params = { encoding: 'base64' };
var img = fs.readFileSync(filename,params);
T.post('media/upload', { media_data: img }, onUpload);
function onUpload(err,data,response) {
var id = data.media_id_string; console.log(id);
// post a tweet /hashtag along with image
var tweet = { status: 'random Study Tweet #giphyBotTweets', media_ids: [id] };
T.post('statuses/update',tweet, tweeted);
}
function tweeted(err,data,response){
if(err)
{
var errors = data.errors;
var i = 0;
for(i = 0 ; i < errors.length; i++)
console.log("Error Message(s) : "+errors[i].message);
}
else
{ console.log(data.text); }
}
}
}
Thanks in advance.
T.post(
"media/upload",
{
media_data: dataImage,
command: "APPEND",
media_id: data.media_id_string,
segment_index: 0
},
function(err, data2, response2) {
T.post(
"media/upload",
{ command: "FINALIZE", media_id: data.media_id_string },
function(err3, data3, response3) {
let tweet = {
status: post.caption,
media_ids: [id]
};
T.post("statuses/update", tweet, function(
err,
data4,
response
) {
if (err) console.log("Something Went wrong", err.message);
if (data4.errors) {
console.log(
"ERROR On Success : ",
data4.errors[0].message
);
} else {
let update = {status: 2, TwitpublishId: data.media_id, updatedAt: Date.now() },
options = { new: true };
Post.findByIdAndUpdate(post._id, update, options, (error, result) => {
if (error) return;
console.log('result video========twit',result);
console.log("Posted on Twitter : https://twitter.com");
});
}
});
}
);
}
);
}
);
}
}

Node.js, Express.js and sqllite3.js

I have a problem with object attributes in Node.js. While attributes are set as expected in the test object, the same doesn't work for my articles object. The difference I see is that the functions of articles are called asynchronously. I must confess that I am a bit lost...
Here is app.js, that instantiates the test object and the articles object.
/**
* Load express.
*/
var express = require('express');
var app = express();
/**
* Load articles.
*/
var articles = require('./article.js');
var l_articles = new articles.Articles();
var test = require('./test.js');
var l_test = new test.Test();
app.get('/', function (req, res) {
console.log(l_test.get());
l_test.set('it is', 'midnight');
console.log(l_test.get());
articles.Articles.get(1);
res.send('OK');
})
app.listen(3001, function () {
console.log(l_test.get());
l_test.set('goodbye', 'sunshine');
console.log(l_test.get());
})
Here is my fairly simple test.js :
var app = require('./app.js');
function Test() {
this.timestamp = new Date();
console.log(this.timestamp);
this.attribute1 = 'hello';
this.attribute2 = 'world';
}
Test.prototype.get = function() {
console.log(this.timestamp);
return (this.attribute1 + ' ' + this.attribute2);
}
Test.prototype.set = function(p_param1, p_param2) {
console.log(this.timestamp);
this.attribute1 = p_param1;
this.attribute2 = p_param2;
}
module.exports = {
Test: Test
};
Here is my fairly simple article.js :
var sqlite3 = require('sqlite3').verbose();
var app = require('./app.js');
function Articles(p_id) {
this.timestamp = new Date();
console.log(this.timestamp);
this.db = new sqlite3.Database('./gescom.sqlite');
if (p_id == undefined) {
this.db.all('SELECT * FROM T_ARTICLE', this.load);
} else {
this.db.all('SELECT * FROM T_ARTICLE WHERE id = ' & p_id, this.load);
}
}
Articles.prototype.load = function(p_err, p_rows) {
console.log(this.timestamp);
var ids = [];
var articles = [];
p_rows.forEach(function(p_row) {
ids.push(p_row.ID);
articles.push([p_row.ID, p_row.SHORT_NAME]);
});
this.ids = ids;
this.articles = articles;
console.log(this.ids.length + ' articles loaded from database.');
}
Articles.prototype.get = function (p_id) {
console.log(this.timestamp);
var l_return;
if ((this.ids == undefined) || (this.articles == undefined)) {
console.log('No articles loaded from database.');
} else {
console.log(this.ids.length + ' articles loaded from database.');
if (p_id == undefined) {
l_return = this.articles;
} else {
if (this.ids.indexOf(p_id) != undefined) {
l_return = (this.articles[this.ids.indexOf(p_id)]);
} else {
l_return = undefined;
}
}
}
return l_return;
}
module.exports = {
Articles: Articles
};

wit.ai : sessionid undefined in my runActions function

I am writing my first apps with wit.ai using a node.js backend. I found some posts here similar to my question, but not really the answer :
I use a socket.io to communicate with my node script.
The two relevant parts of my node are :
io.sockets.on('connection', function (socket) {
socket.on('message',
function(data) {
var json = JSON.parse(data);
var sid = json['sessionid'];
console.log("Received on sid " + sid);
if (_sessions[sid] == undefined) {
_sessions[sid] = {};
_sessions[sid].context = {};
}
_sessions[sid].socket = socket;
client.runActions(sid, json['text'], _sessions[sid].context, 30)
.then((context) => {
_sessions[sid].context = context;
}
)
.catch((err) =>
{
console.error('Oops! Got an error from Wit: ', err.stack || err);
}
);
}
);
}
);
========
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
return new Promise(function(resolve, reject) {
var session = _sessions[sessionId];
console.log("-------------------------------");
console.dir(context);
console.log("-------------------------------");
session.socket.emit("message", JSON.stringify(response));
return resolve();
});
},
gettaxi ({sessionid, context, text, entities}) {
return new Promise(function(resolve, reject) {
console.log(`Session ${sessionid} received ${text}`);
var quand = firstEntityValue(entities, "quand");
if (!quand && context['quand'] != undefined) quand = context['quand'];
var depart = firstEntityValue(entities, "depart");
var arrivee = firstEntityValue(entities, "arrivee");
if (depart) {
console.log("Found depart");
context.depart = depart;
delete context.missing_depart;
}
else {
context.missing_depart = true;
}
if (arrivee) {
console.log("Found arrivee");
context.arrivee = arrivee;
delete context.missing_arrivee;
}
else {
context.missing_arrivee = true;
}
console.dir(context);
if (quand) {
console.log("Found quand");
context.quand = quand;
delete context.missing_quand;
}
else {
context.missing_quand = true;
}
return resolve(context);
}
);
},
};
All is working rather good, except than my gettaxi receives a undefined sessionid.
It's not the case for the send function that receives the correct sessionid.
What am I doing wrong ?

Resources