"message": "Cannot read properties of undefined (reading 'split')",
+ "stack": "TypeError: Cannot read properties of undefined (reading 'split')
+ at /Users/dhruv/code/c0485f/src/api/posts.js:66:31
+ at Layer.handle [as handle_request] (/Users/dhruv/code/c0485f/node_modules/express/lib/router/layer.js:95:5)
+ at next (/Users/dhruv/code/c0485f/node_modules/express/lib/router/route.js:144:13)
+ at Route.dispatch (/Users/dhruv/code/c0485f/node_modules/express/lib/router/route.js:114:3)
+ at Layer.handle [as handle_request] (/Users/dhruv/code/c0485f/node_modules/express/lib/router/layer.js:95:5)
+ at /Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:284:15
+ at Function.process_params (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:346:12)
+ at next (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:280:10)
+ at Function.handle (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:175:3)
+ at router (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:47:12)",
I am getting this error from the code attached below and while calling this API there is data in body "authorIds"
router.get('/', async (req, res, next) => {
try {
const { authorIds, sortBy = 'id', direction = 'asc' } = req.body;
//if access token is not verified then this statemnt will throw an error.
jwt.verify(req.headers['x-access-token'], process.env.SESSION_SECRET);
//finding all posts which all are associated with authorIds got from request.
const posts = await Post.findAll({
order: [[sortBy, direction]],
include: [
{
model: UserPost,
required: true,
attributes: [],
where: {
userId: authorIds.split(","),
},
},
],
});
//console.log(posts);
res.json({ posts });
} catch (error) {
if (error.name === 'JsonWebTokenError') {
return res.status(401).json({ error: error.message });
}
next(error);
}
});
make sure you are sending the authorIds in request body and its value is valid and make sure you use express.json() middleware in your express app at the start so it can parse the body.
app.use(express.json());
and one more thing
you are trying to read request body from a get request!
get request cant carry a body, only query param and path param and headers are allowed.
turn it to a post request or send params in query or path.
Related
When trying to list the payment methods owned by the customer from the backend server, I'm getting this error. Stripe documents have an API on the same name but it doesn't seem to work in my case. I need to fetch all the payment methods in my backend and send them back to the client side for future use.
API reference: https://stripe.com/docs/api/payment_methods/list
Code:
app.post("/savedCards", cors(), async (req, res) => {
let { customerId, paymentMethodId } = req.body;
const paymentMethods = await stripe.customers.listPaymentMethods(
'cus_M3nQBIvz9qykuG',
{type: 'card'});
console.log(paymentMethods);
res.status(200).send(paymentMethods.data[0].card);
} catch (err) {
console.log(err);
res.status(500).json({ message: "Internal server error" });
}
});
Error:
TypeError: stripe.customers.listPaymentMethods is not a function
at C:\Users\rekha d\OneDrive\Desktop\test_cards\card-section\server\index.js:72:51
at Layer.handle [as handle_request] (C:\Users\rekha d\OneDrive\Desktop\test_cards\card-section\server\node_modules\express\lib\router\layer.js:95:5)
\server\node_modules\cors\lib\index.js:214:15)
at C:\Users\rekha d\OneDrive\Desktop\test_cards\card-section\server\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\rekha d\OneDrive\Desktop\test_cards\card-section\server\node_modules\cors\lib\index.js:199:9)
at corsMiddleware (C:\Users\rekha d\OneDrive\Desktop\test_cards\card-section\server\node_modules\cors\lib\index.js:204:7)
at Layer.handle [as handle_request] (C:\Users\rekha d\OneDrive\Desktop\test_cards\card-section\server\node_modules\express\lib\router\layer.js:95:5)
You need at least version v8.180.0 of the Stripe Node library to list payment methods this way.
The error is telling you that listPaymentMethods isn't a function. It looks like per Stripe docs, it should be stripe.paymentMethods.list, rather than stripe.customers.listPaymentMethods:
const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc');
const paymentMethods = await stripe.paymentMethods.list({
customer: 'cus_9utnxg47pWjV1e',
type: 'card',
});
Or, as mentioned in the comments below, you can upgrade to the newer version of the stripe-node library where listPaymentMethod is a valid method.
I want to make a bot dashboard in Discord.js and EJS.
I have an error.
>> 1| <%- include('blocks/header', {bot, user, path})%>
bot is not defined
at eval (/app/dashboard/index.ejs:10:43)
at index (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/ejs/2.7.4/node_modules/ejs/lib/ejs.js:682:17)
at tryHandleCache (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/ejs/2.7.4/node_modules/ejs/lib/ejs.js:254:36)
at View.exports.renderFile [as engine] (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/ejs/2.7.4/node_modules/ejs/lib/ejs.js:485:10)
at View.render (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/view.js:135:8)
at tryRender (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/application.js:640:10)
at Function.render (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/response.js:1012:7)
at app.get (/app/util/dashboard.js:45:7)
at Layer.handle [as handle_request] (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/layer.js:95:5)
But I have it defined.
const renderTemplate = (res, req, template, data = {}) => {
const baseData = {
bot: client,
path: req.path,
user: req.isAuthenticated() ? req.user : null
};
res.render(templateDir + path.sep + template, {baseData, data});
};
I have a include tag in my index.ejs file.
<%- include('blocks/header', {bot, user, path})%>
For any help, thank you!
The way around this would be to render it differently;
const renderTemplate = (res, req, template, data = {}) => {
res.render(templateDir + path.sep + template), {
bot: client,
path: req.path,
user: req.isAuthenticated() ? req.user : null
data: data
})
};
I'm using NodeJS with express, consign, body-parser, etc.
I'm trying to load a module in a var, so i can use their functions, but i'm getting a:
TypeError: Cannot read property 'listar' of undefined
at app.get (/home/sartori/Documentos/Projetos/react-system/api/controllers/autores.js:6:11)
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
at next (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
at /home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:335:12)
at next (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:275:10)
at /home/sartori/Documentos/Projetos/react-system/api/node_modules/express-validator/lib/express_validator.js:250:5
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
Here's my controller:
module.exports = app => {
app.get('/api/autores', (req,res) => {
let connection = app.connection.connectionFactory();
let autores = app.models.AutoresDao(connection);
autores.listar((error,result) => {
if(error) {
console.log('Erro ao listar os autores: ' + error);
res.status(500).send(error);
} else {
res.json(result);
}
});
});
}
Here's the AutoresDao:
function AutoresDao(connection) {
this._connection = connection;
}
AutoresDao.prototype.listar = callback => this._connection.query('SELECT * FROM autores', callback);
module.exports = function() {
return AutoresDao;
}
The problem is: Cannot read property 'listar' of undefined.
Apparently the problem is loading the AutoresDao file.
I'm 100% sure of files path, AutoresDao is inside models folder, already loaded on consign. The same for the controller, connection, express config etc.
Any idea of what i'm doing wrong?
You need to be using the 'new' keyword if you are going to format your object constructor function in that manner. You will have to reformat your AutoresDao function to explicitly return an object, or use the 'new' keyword when you assign it to autores in the controller.
Please checkout this article for an explanation of the different instantiation patterns.
https://medium.com/dailyjs/instantiation-patterns-in-javascript-8fdcf69e8f9b
Hope that helps! Cheers.
I use supertest to test my RESTful API which develop by express, but I encountered a problem. The following the debug message.
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header \nodejs-framework\node_modules\express\lib\response.js:719:10)
at ServerResponse.send \nodejs-framework\node_modules\express\lib\response.js:164:12)
at done \nodejs-framework\node_modules\express\lib\response.js:956:10)
at View.exports.renderFile [as engine] \nodejs-framework\node_modules\ejs\lib\ejs.js:355:10)
at View.render \nodejs-framework\node_modules\express\lib\view.js:126:8)
at tryRender \nodejs-framework\node_modules\express\lib\application.js:639:10)
at EventEmitter.render \nodejs-framework\node_modules\express\lib\application.js:591:3)
at ServerResponse.render \nodejs-framework\node_modules\express\lib\response.js:960:7)
at D:\H60\H60_New\nodejs-framework\app.js:216:13
at Layer.handle_error \nodejs-framework\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix \nodejs-framework\node_modules\express\lib\router\index.js:310:13)
at D:\H60\H60_New\nodejs-framework\node_modules\express\lib\router\index.js:280:7
at Function.process_params \nodejs-framework\node_modules\express\lib\router\index.js:330:12)
at next \nodejs-framework\node_modules\express\lib\router\index.js:271:10)
at D:\H60\H60_New\nodejs-framework\node_modules\express\lib\router\index.js:618:15
at IncomingMessage.next \nodejs-framework\node_modules\express\lib\router\index.js:256:14)
at done \nodejs-framework\node_modules\express\lib\response.js:955:25)
at tryRender \nodejs-framework\node_modules\express\lib\application.js:641:5)
at EventEmitter.render \nodejs-framework\node_modules\express\lib\application.js:591:3)
When I use supertest.agent(envFile.API_SERVER.url) as test target, it will pass forever,
but while I use supertest.agent(envFile.API_SERVER.app) which is a enter point in my project, it will be failed when I need to respond in middleware.
The following, is my code in my middleware.
let paramObj = {
account: -1,
pw: -2,
email: -3,
},
paramObjKey = Object.keys(paramObj);
for ( let param of paramObjKey ) {
if ( typeof req.body[param] === "undefined" ) {
res.json(paramObj[param]);
return;
}
}
next();
I have another middleware which will handle exceptions, and it is the root cause in this problem. It will respond again after the previous middleware has responded.
app.use(function(err, req, res, next) {
if ( !typeService.isNull(err) ) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
}
});
You can't send responses multiple times.
Having res.json(paramObj[param]); inside a for loop sends a response each iteration.
You need to send the response only once.
I agree w/ #Swaraj.
Change the return in your for loop to break instead.
let paramObj = {
account: -1,
pw: -2,
email: -3,
},
paramObjKey = Object.keys(paramObj);
for ( let param of paramObjKey ) {
if ( typeof req.body[param] === "undefined" ) {
res.json(paramObj[param]);
break;
}
}
next();
This will break out of the for loop and execute the next link in the middleware chain.
I'm starting with Parse and Node.js. I'm trying to retrieve data from Parse db and I don't manage to.
var Parse = require('parse').Parse;
Parse.initialize("*************", "*****************");
module.exports = {
index: function(req, res, next){
var query = new Parse.Query(Parse.Event);
query.find({
success: function(results) {
console.log(results);
},
error: function(error) {
console.log(error.message);
}
});
}
}
And I got this error :
TypeError: Cannot read property 'prototype' of undefined
at Object.Parse.Query (/Users/tchiss_a/test/webapp/node_modules/parse/build/parse-latest.js:7771:33)
at module.exports.index (/Users/tchiss_a/test/webapp/api/Events.js:7:20)
at Layer.handle [as handle_request] (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/layer.js:82:5)
at /Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:235:24
at Function.proto.process_params (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:313:12)
at /Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:296:3)
Can someone help me please ?
There is a fix listed in the comments, but the actual problem here is that you're treating a user-defined class "Event" like a Parse class.
change
var query = new Parse.Query(Parse.Event);
to
var query = new Parse.Query("Event");