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

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

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)

Can't export multiple modules [ExpressJs]

this my error: Route.get() requires a callback function but got a [object Object]
module.exports = getAccessToRoute;
I don't get an error when I export as,
But
module.exports = { getAccessToRoute, getAdminAccessToken };
when i export like this i get error.
I don't have problem nother middleware.
I forgot the parentheses when calling from within another router.
const getAccessToRoute = require('../middlewares/authorization/auth');
i fixed it like this
const { getAccessToRoute } = require('../middlewares/authorization/auth');

Node Js API : where the undefined comes from?

I write this code to get the array from url. this is the url : http://localhost:3000/main?a=aaa.jpg&a=bbb.jpg
And here is the code :
//Define module
var express = require('express');
var app = express();
const { exec } = require('child_process');
//extract function
function extract (req,res,next){
res.write(`filename : ${req.query.a}`); //kt page
console.log(req.query.a);//kt terminal
next();
};
//main function
function main (req,res,next){
res.write('\nkuor dok \n');
res.end();
};
app.use(extract);
app.get('/main',main);
app.listen(3000);
This is the output in terminal.
Array(2) ["aaa.jpg", "bbb.jpg"]
undefined
The question is where the undefined comes from? It affected everything i need to do. The array is perfectly fine. But suddenly undefined comes out. Can anyone help me. Thank you in advance.
I tried the code you provided above and i got only the array in the terminal
[ 'aaa.jpg', 'bbb.jpg' ]
When i tried the url in the browser i got
filename : aaa.jpg,bbb.jpg
kuor dok
as the output. i didn't get any undefined
I see that you are trying to define extract function as a middleware. It will be executed for every request
try to comment app.get:
app.use(extract);
//app.get('/main', main);
app.listen(3000);
Then try to make the request
GET: http://localhost:3000/main?a=aaa.jpg&a=bbb.jpg
you will get
[ 'aaa.jpg', 'bbb.jpg' ]
You are handling the request twice. First by the global middleware, the second time by app.get() that calls also the middleware extract before main
As I see app.get don't handle your query params and you got undefined due to an empty object try to log: req.query intead of req.query.q
function extract(req, res, next) {
res.write(`filename : ${req.query.a}`); //kt page
console.log(req.query); //kt terminal
next();
};

Undefined Variable in JSON Object in Node Module

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.

Undefined when trying to use Spy

Using my code:
it('should start application only once', function(done){
var spy = sinon.spy(server, 'startup');
var calledOnce = spy().calledOnce;
calledOnce.should.be.true;
done();
});
I get the error:
Cannot read property should of undefined.
The calledOnce variable is undefined. I'm doing something wrong in how I setup the spy and use it. How can I fix this?
Startup is a method in my object that I exported from a server.js file.
If you want to see if a particular function/method has been called, you need to spy on it before it gets called (otherwise the spy won't know about it):
var server = ...
var spy = sinon.spy(server, 'startup');
server.startup(...);
spy.calledOnce.should.be.true;

Resources