Vue.js Nuxt - cannot access Array (value evaluated upon first expanding error) - vue.js

I have the following function which gives me an array called URLs
const storageRef = this.$fire.storage.ref().child(fileName)
try {
const snapshot = storageRef.put(element).then((snapshot) => {
snapshot.ref.getDownloadURL().then((url) => {
urls.push(url)
})
})
console.log('File uploaded.')
} catch (e) {
console.log(e.message)
}
});
console.log(urls)
console.log("about to run enter time with imageurls length " + urls.length)
When I run console.log(URLs) initially I do see the array like the following
[]
0: "testvalue"
length: 1
__proto__: Array(0)
However, there is a small information icon stating
This value was evaluated upon first expanding. The value may have changed since.
Because of this, when I try to get the length of URLs, I get zero, meaning the value is being updated.
Does anyone know what's happening? I am using Vue.JS/Nuxt.

Related

Can not res.send() (error: "Cannot set headers after they are sent to the client") after I do query to database PostgrSQL

I know, it sounds really wierd, but it's true.
I was sitting and making an API on node.js, but when I began to test it, I was surprised to find out that nearly in beginning of query treatment when the first res.status().send() reached, VS Code drop a "Cannot set headers after they are sent to the client" error.
How I realize that database query is guilty? I used "res.finished" property to check out when it "sent to client" and discovered that res.finished changes from "false" to "true" exactly after db query.
Who knows what it can be? I had done the same API thing with MySQL database and it went nice, but now I'm using PostgreSQL, so things start to happen.
I export "PostgreSQL manager" class from typescript file
PostgreSQL_Manager.ts:
module.exports = {
PostgreSQL_db_manager
}
Import and initialize it in index.ts:
index.ts
const PostgreSQL_mngr = require('./PostgreSQL_Manager.ts').PostgreSQL_db_manager;
const db = new PostgreSQL_mngr;
And then, if I comment the statement with query to database, res.finished stay false (I tried it with readRows (SELECT) and with createRows(INSERT INTO)):
Piece of index.ts code:
console.log('res.finished : ', res.finished);
//let nickval : any = await db.readRows('users', 'nickname', `nickname = \'${nickname}\'`);
//await db.createRows('test', '(color, odor, taste, quantity)', '(\'meaningless\', \'absent\', \'sadness\', 0)');
console.log('res.finished : ', res.finished);
Piece of Terminal:
res.finished : false
res.finished : false
But when I uncomment database query, it becomes this:
Piece of index.ts code:
console.log('res.finished : ', res.finished);
//let nickval : any = await db.readRows('users', 'nickname', `nickname = \'${nickname}\'`);
await db.createRows('test', '(color, odor, taste, quantity)', '(\'meaningless\', \'absent\', \'sadness\', 0)');
console.log('res.finished : ', res.finished);
Piece of Terminal:
res.finished : false
Postgres: Rows were created...
res.finished : true
Code of db.createRows in postgres manager class looks like this:
public async createRows(table : string, columns: string | string[], values: string | string[]) : Promise<void> {
let createPromise = new Promise<void> ((resolve, reject) => {
this.db.query(`INSERT INTO ${table} ${columns} VALUES ${values};`, (err) => {
if(err) throw err;
console.log('Postgres: Rows were created...');
resolve();
});
});
await createPromise;
}
Edit 1:
There is error occurs (This function called from app.post, nickname, email and password has string values):
async function validationUsers (res : any, email : string = undefined, password : string = undefined, nickname : string = undefined) : Promise<boolean> {
console.log('f:validationUsers email : ', email);
console.log('f:validationUsers password : ', password);
console.log('f:validationUsers : nickname', nickname);
//validation: nickname and email
if(nickname) {
console.log('res.finished : ', res.finished);
//let nickval : any = await db.readRows('users', 'nickname', `nickname = \'${nickname}\'`);
await db.createRows('test', '(color, odor, taste, quantity)', '(\'meaningless\', \'absent\', \'sadness\', 0)');
console.log('res.finished : ', res.finished);
/* if(nickval[0] !== undefined) {
console.log('frofkofro');
res.status(410).send('Nickname already exists');
res.end();
return false;
} */
}
//validation: email
if(email) {
let emailval : any = await db.readRows('users', 'email', `email = \'${email}\'`);
console.log('f:validationUsers if(email) emailval[0] : ', emailval[0]);
if(emailval[0] !== undefined) {
console.log("?00");
res.send('Email already exists');
res.end();
return false;
}
}
//validation: password
if(password) {
let passwordval = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,100}$/;
if(!password.match(passwordval)) {
console.log('password BAM!!!');
res.status(412).send('Password does not match the criteria'); <-- **THIS STRING**
console.log('password BOOM!!!');
//res.end();
return false;
}
}
console.log('End of f:validationUsers');
return true;
}
Edit 2:
Can it be some problem with pool.query or pool connection to database from "pg" library for PostgreSQL? Or maybe problem with ts-node compiler?
So, I really don't understand what's going on.
I don't know if it's important, but I use ts-node for compile and render typescript
Edit 3:
OKAY, so I started in new ts file new server with the same 5000 port and run THIS:
app1.get('/db', async (req : any, res : any) => {
console.log('res.finished : ', res.finished);
await db1.createRows('test', '(color, odor, taste, quantity)', '(\'meaningless\', \'absent\', \'sadness\', 0)');
console.log('res.finished : ', res.finished);
res.status(200).send('All is fine this is send');
res.end();
});
And result in console:
Connected to database as pool successfully...
Server started on port 5000
res.finished : false
Postgres: Rows were created...
res.finished : false
And POSTMAN received res.send(). wtf??????
The error 'Headers already sent...' happens when your PostgreSQL code sends multiple results using res.send().
I assume the res.send() part is within PostgreSQL manager, which looks like a tested and true library - so what is happening to make it send two answers to one query?
I have no experience with Typescript and pSQL, but I have worked with pSQL and remember hitting this same snag years ago.
PostgreSQL supported (and I imagine it still supports) multiple query mode, such as, UPDATE b SET a=2 WHERE c; SELECT a FROM b. Those are two statements, and the reason why some exploits can even work.
And, just like it happened to me once, even if the second one has zero length and apparently is not even a query, in your code
`INSERT INTO ${table} ${columns} VALUES ${values};`
your PostgreSQL Manager just might think that there are two statements.
So, try removing that apparently harmless ';' at the end and see whether it solves the problem. I wasn't using your libraries, but for me, that did it.
I would say that the error is comming from here :
res.send('Email already exists');
res.end();
Indeed if you node's doc reads :
The res.end() function is used to end the response process. This method actually comes from the Node core, specifically the response.end() method of HTTP.ServerResponse. Use to quickly end the response without any data.
given that you already responsed 'Email already exists' express.js, you recieve the error message Cannot set headers after they are sent to the client (it just means you have already sent a response)
I think just removing res.end(); would fix your issue.
Okay, it's really strange and wierd. I have middleware function app.use and it looked something like that:
app.use(async function (req : any, res : any, next : any) {
console.log(smthng);
get('header') stuff;
if (cond) {
// this is not executed because condition was false in all my situation
} else {
// this is executed in all cases of this thread
req.name = undefined;
next();
}
next()
})
As you see, in the end of middleware function was next(). So, I removed JUST THIS NEXT AND:
Terminal:
res.finished : false
Postgres: Rows were read...
[]
res.finished : false
res.finished : false
Postgres: Rows were read...
[]
f:validationUsers if(email) emailval[0] : undefined
res.finished : false
password BAM!!!
password BOOM!!!
I do not know what happened, I think this is deepsea shizophrenic hyperfluid flows under complier with some crossroad between db promise, middleware and res.send()

TypeError: Cannot read property 'replace' of undefined in the context of VueJS

I am filtering some of the characters from the string. I went across few questions which has a same problem ie error in the console, but could not find any good answers.
Here is my string:
response_out1|response_out2|response_out3
Here is the method that i have used:
<vs-select v-model="change">
<vs-select-item :key="index" v-bind="item" v-for="(item,index) in
userFriendly(out.changes)" />
</vs-select>
...
methods: {
userFriendly (str){
return str.replace(/_/g, ' ').split('|').map(value => ({text: value, value }))
}
Here is the output that i am getting in the vs-select:
response out1
response out2
response out3
The error that i am getting in my console:
Here i want to know why i am getting this error and i wanna know how to rectify it and the output that i am expecting is: Response Out1, here how to capitalize first character of each word in the same method.
you're using a method directly in the template which causes multiple calls whenever your data changes,
you can use computed property to avoid such a scenario, not sure about how you are accessing out.changes
this might help you to solve your error and capitalize your text,
capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
sentenceCase (sentence) {
return sentence.split(' ').map(s => this.capitalize(s)).join(' '));
},
userFriendly (str) {
if (!str) return;
return str.replace(/_/g, ' ').split('|').map(value => ({text: this.sentenceCase(value), value }))
},

Cypress | Cant change variable inside each loop

OK, So, I have this code:
Cypress.Commands.add ('MethodName', (argument) => {
var Fails = 0
cy.get('anything').each(Id => {
if (blablabla) {
Fails += 1
cy.log("Inside the each: " + Fails) //prints 1
}
})
cy.log("Outside the each: " + Fails) //prints 0
});
I want to test each item and if a condition is wrong, I want to add 1 to the variable "Fails".
Then, in the end, if Fails is 0, then there are no errors, and I want it to log the message "NO FAILS". The problem is , even if the variable changes to 1 inside the EACH, when its outside, it comes back to 0.
This is so frustrating to me, because Im used to write C# code and in C#, that would work, since the declaration of the variable is outside the each.
What do you guys suggest?
JavaScript runs asynchronously which means that your codes doesn't run in sequence. So what's happening in your case is Outside the each: is executing first and after that Inside the each: is being executed. To make sure that Outside each runs after inside each, you have to use then().
Cypress.Commands.add('MethodName', (argument) => {
var Fails = 0
cy.get('anything').each(Id => {
if (blablabla) {
Fails += 1
cy.log("Inside the each: " + Fails)
}
}).then(() => {
cy.log("Outside the each: " + Fails)
})
})

Accessing elements in JSON for nodejs

first off I am very new to node/JSON, so please take that into consideration when reading through.
The purpose of this code is to take data from a SQL Server database, and be able to access the elements that it pulls. For example, it will pull several thousand parentacccount ID's, and I just want to access one of those.
I've browsed forums for almost the entire day trying to access JSON elements from my nodejs function, and I every time I try and access one of these elements I am hit with an "undefined" error. As a last resort I am here.
I have checked a few times to see recordset has been parsed, and it appears that it is being parsed.
Below is my code, and a very small example of the JSON code is towards the end.
I have commented where I am getting my error.
function getEmp() {
var conn = new sql.ConnectionPool(dbConfig);
var req = new sql.Request(conn);
conn.connect(function (err) {
if (err) {
console.log(err);
return;
}
req.query("SELECT * FROM parentaccount Where accountname like 'Titan%' FOR JSON PATH", function (err, recordset) {
if (err) {
console.log(err);
}
else {
const Test1 = recordset[0].ParentAccountId; //error here
console.log(Test1);
}
conn.close();
})
})
}
getEmp();
//EXAMPLE JSON
{ recordsets: [ [ [Object] ] ],
recordset:
[ { 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B':
'[{"ParentAccountId":4241411,"AccountName":"Titan"} ],
output: {},
rowsAffected: [ 3 ] }
ERROR:
TypeError: Cannot read property 'ParentAccountId' of undefined
at C:\Users\za47387\Desktop\Excel Export Code\test2.js:31:48
at _query (C:\Users\za47387\node_modules\mssql\lib\base.js:1347:9)
at Request.tds.Request.err [as userCallback] (C:\Users\za47387\node_modules\mssql\lib\tedious.js:671:15)
at Request.callback (C:\Users\za47387\node_modules\tedious\lib\request.js:37:27)
at Connection.endOfMessageMarkerReceived (C:\Users\za47387\node_modules\tedious\lib\connection.js:2104:20)
at Connection.dispatchEvent (C:\Users\za47387\node_modules\tedious\lib\connection.js:1084:36)
at Parser.tokenStreamParser.on (C:\Users\za47387\node_modules\tedious\lib\connection.js:914:14)
at Parser.emit (events.js:189:13)
at Parser.parser.on.token (C:\Users\za47387\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:189:13)
From what the sample you have shared,
recordset[0] is undefined, meaning either two options :
a) the result for the query fetched no rows.
b) the result of the query is in a different format than expected.
though i suspect a), its good to console the output. kindly run the below code before you try accessing ParentAccountId.
console.log('output : ', JSON.stringify(recordset, null, 4));
also i would refactor the code to be :
const Test1 = (Array.isArray(recordset) &&
recordset.length) ? recordset[0].ParentAccountId : null;
so that the error won't make the nodejs process go down.

Items: Get item revision difference returns empty array

I am trying to return the diffence in field values between two revisions using app authentication but I'm getting an empty array.
And when trying to use the api function "Get Item revision" I'm getting "Object not found" response.
Any help would be much appreciated :)
const podio = new Podio({
authType: 'app',
clientId: clientId,
clientSecret: clientSecret });
podio.authenticateWithApp(app_id, appToken, (err) => {
if (err) throw new Error(err);
podio.isAuthenticated().then(function () {
// ready to make API calls
apiRoutes.get('/item', function (req, res) {
podio.request('GET', `/item/702620400/revision/1899410196/1910867632`).then(function (responseData) {
res.json(responseData);
});
});
}).catch(err => res.send(err));
});
Podio documentation is not clear enough when describes calls for item revisions. Here is how it works, example in Ruby:
item_revisions = Podio::ItemRevision.find_all_by_item_id(item_id)
last = item_revisions.length - 1
revision_last = Podio::ItemRevision.find(item_id, last)
revision_beforelast = Podio::ItemRevision.find(item_id, last - 1)
diff = Podio::ItemDiff.find_by_item_and_revisions(item_id, last - 1, last)
Misleading part is revision_id vs revision vs item_revision_id.
For "Get Item revision" and "Get item revision difference" calls please use revision which goes for each item from 0 and increases by 1 with each new revision. Last revision available for item is item_revisions.length - 1 from example above.