Undefined Variable in JSON Object in Node Module - node.js

I can't figure out why I get an undefined here for 'app':
module.exports = {
application: require('../../app').service,
request: require('supertest')(this.application),
startSetup: setup(this.application)
};
it throws up at the (this.application) for the request: line.

Yo can try this:
var app = require('../../app').service;
module.exports = {
application: app,
request: require('supertest')(app),
startSetup: setup(app)
};
The problems is that this.application doesn't exists yet.
You can't use the inside parts of an object that it is not defined (it is defined only after the final }).
Here is an example that you can try on your chrome console.
You can see that you can't use type because it is not defined.

Javascript doesn't know what this.application is. The object hasn't been defined yet so you can't use an attribute inside at object definition that's defined in the same object.

Related

Cannot read properties of undefined using "This" in JavaScript class

I'm using Node JS and ExpressJS to write my web server. I use JavaScript OOP fromfew time. I get an error running this class:
class myClass {
constructor(path) {
this.path = path;
}
myFunction(){
var fileControllerInstance = new FileController(this.path);
fileControllerInstance.fileExist(function(fileExist) {
if(fileExist){
console.log("file exist");
this.printLine("test");
}
else
return false;
});
}
printSTR(str){
console.log(str);
}
}
new myClass("filePath").myFunction();
module.exports = myClass;
Running this class I get an error on printSTR function. Error is the follow:
file exist
TypeError: Cannot read properties of undefined (reading 'printSTR')
Without this I get ReferenceError: printSTR is not defined. To solve my problem I need to create another class instance and to use that to call the function. Something like this:
new myClass("filePath").printSTR("test") instead to ``` this.printLine("test"); ```
Why using this my code not working? Thanks
Inside the function(fileExist), this has a different value than outside. To inherit the value inside, you must bind the function:
fileControllerInstance.fileExist(function(fileExist) {
...
}.bind(this));
You're calling this inside a callback. You can find this post useful to solve your issue.
Also you try to call printLine("test") but your method is printSTR(str)

Koa cannot get the value of the property inside ctx.request-body

Koa cannot get the value of the property inside ctx.request-body
Project koa is generated by koa-generator
Routing section related code
Either require('koa-body') or require('koa-bodyparser')
console.log("ctx")
console.log(ctx.request.body)
console.log(ctx.request.body.type)
})
The three console.log prints are
ctx
{
account:'root',
password: 'test',
type:0
}
undefined
I can get the object inside the ctx.requisition.body and print it out, but ctx.request.body.type is undefined
How to get 'ctx.requisition.body.account' or 'ctx.requisition.body.password' ?
Maybe if you do this
const myObj = JSON.parse(ctx.request.body)
console.log(myObj.type)
You'll get ctx.request.body.type

Using aws-sdk.js with require.js in a browser

I'm trying to figure out how to use the browser-based aws-sdk.js with require.js when building a web app.
If I try to build a class and include aws-sdk in the require.js define, once I try to create an instance and reference the AWS class, it says it is undefined.
For example, I have a function that checks to see if the credentials are an instance of AWS.Credentials and if not, it tries to initialize it with an STS token it retrieves via Rest.
The problem is, the code dies on the if(this.credentials instanceof AWS.Credentials) saying AWS is undefined. It even dies on my simple check of the needsRefresh.
This is what my define looks like - I'll include the 'needsRefresh' wrapper for an example of the sort of thing that is throwing the Undefined error:
define(['require','aws-sdk','jquery'],
function (require, AWS, $) {
// Aws helper class
function AwsHelper() { };
AwsHelper.prototype = {
credentials: null,
tokenNeedsRefresh: function () {
//////////////////////////////////////////////////////////////////
// errors out on the following line with: //
// TypeError: Cannot read property 'Credentials' of undefined //
//////////////////////////////////////////////////////////////////
if(this.credentials instanceof AWS.Credentials) {
return this.credentials.needsRefresh();
} else return true;
}
};
return AwsHelper;
}
);
I also tried the following format at the top of the file:
define(function (require) {
var AWS = require("aws-sdk"),
$ = require("jquery");
/* .. */
If I remove all onLoad references to the refresh code running, it will load and I can create an instance. But as soon as I call any function that references the AWS class, it dies.
How do I make sure that AWS class definition is still in global space once an instance is spawned?
Dunno what difference the paths will make (it's finding and loading the code just fine - I can see AWS Class in namespace in the debugger as it's loading but it's not in the namespace on the function call), but added on request:
requirejs.config({
baseUrl: '/js',
paths: {
lib: 'lib',
ImageUploader: 'ImageUploader'
}
});
I decided to try to play with this again and seemed to have figured out how I was going about it incorrectly. I have yet to integrate it back into my existing code setup, but I think I have a working solution.
The thing I was doing wrong was I was trying to set up the AWS class so I could load it as a module (thus why I tried wrapping it as the require.js suggested).
Playing with it this time around, I noticed something I hadn't before. I had an AWS that was undefined in the local scope and an other AWS that held the class definition in the global scope. So it was trying to specify AWS in my define that was creating the local 'null' version:
define(
["jquery","aws-sdk","dropzone","app/MyUtilities"],
function ($, AWS, Dropzone, MyUtilities) {
"use strict";
function MyClass() {};
return MyClass;
}
);
jquery and dropzone have whatever is needed to make sure they load that way, but aws-sdk seems to do some of it's own asynchronous loading. Thus the scope variable in the function is undefined.
Technically, it seems the only thing I needed defined as a module in the function wrapper is my own utilities module. So by switching it to:
define(
["app/MyUtilities","jquery","aws-sdk","dropzone"],
function (MyUtilities) {
"use strict";
function MyClass() {};
return MyClass;
}
);
... it seems $ and jquery are defined as needed, Dropzone is defined as needed and AWS is defined as needed. (and I don't get my errors when accessing the static AWS.config or AWS.Credentials definitions as I did before)

trying to stringify sails.config.global, circular structure error

I'm getting an error when trying to stringify a global variable in sails:
TypeError: converting circular structure to JSON.
I know what the error means, but the question is, what's happening that's causing there to be a circular reference. And, why does it happen to my custom variable?
Then the next question is: how can I stringify the object the way I created it in globals.js?
In config/globals.js:
module.exports.globals = {
mystuff: {
Url: "http://localhost:8080",
APIKey: "2bb67717b99a37e92e59003f93625c9b"
}
}
In a hook initialize:
module.exports = function (sails) {
return {
initialize: function(cb) {
var str = JSON.stringify(sails.config.globals.mystuff);
}
}
}
This helped identify circular culprits:
Detecting and fixing circular references in JavaScript
Another portion of the app was injecting objects into the globals.

Photoswipe and Require.js configuration

I have a module which is dependent upon both, PhotoSwipe and PhotoSwipeUI_Default. I am requiring both modules, like so and inside of my module I am initialising my gallery. EG:
define("modules/lightboxStart", ["vendor/PhotoSwipe", "vendor/PhotoSwipeUI_Default"], function (PhotoSwipe, PhotoSwipeUI_Default) {
var StartGallery = function(){
var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, items, options);
lightBox.init();
}
StartGallery()
}
The gallery then works as expected but require is throwing a mismatched anonymous define module error in PhotoSwipe.js.
After looking through the docs I came to the conclusion that I need to run both scripts(PhotoSwipe and PhotoSwipeUI_Default) through the require.js API.
I then defined each, like so:
define('PhotoSwipe', function() {
//PhotoSwipe script here
return PhotoSwipe
})
And
define('PhotoSwipeUI_Default', function() {
//PhotoSwipeUI_Default script here
return PhotoSwipeUI_Default
})
This then eliminates the mismatched anonymous define module error I was getting earlier, but I am getting this error now instead:
PhotoSwipe is not a function
How could I fix this? I am essentially trying to access the PhotoSwipe function within PhotoSwipe.js and pass through my arguments but I am unable to do so without generating a load of js errors on the page and I can not figure out why.
Help much appreciated!
define( ["modules/lightboxStart", "vendor/PhotoSwipe", "vendor/PhotoSwipeUI_Default"], function (lightboxStart, PhotoSwipe, PhotoSwipeUI_Default) { //i think so}

Resources