Other than GET all APIs work seamlessly. The problem i am not able to figure out please help me in getting this through.
/**
* @swagger
* /admin/get_all_languages:
* get:
* produces:
* - application/json
* summary: Get all languages.
* description: This API fetches all the languages.
* tags:
* - Admin
* security:
* - JWTAuth: [] # Specify JWT as the authentication method
* responses:
* '200':
* description: Successful response - Fetched all languages successfully.
* content:
* application/json:
* schema:
* type: array # Adjust this based on the actual response structure
* '401':
* description: Unauthorized. JWT token is missing or invalid.
* '500':
* description: Internal server error.
*/
this.router.route('/get_all_languages').get(AuthService.authenticateToken, AdminController.getAllLanguages);
when i hit this i get this error
error: ::1 HTTP/1.1 500 GET /api/v1/admin/get_role_for_assigning - Cannot read property 'lastIndexOf' of undefined (#unknown) : ServerError: Cannot read property 'lastIndexOf' of undefined at Function.get
this is how cors has been handled
private options: Record<string, unknown> = {
cors: {
origin: (origin: string, callback: ( error: Error, status?: boolean ) => void) => {
// origin = origin.trim(); // to remove extra space
console.log("Request Origin",origin)
if (AUTHORIZED.indexOf(origin) !== -1) {
// if (authorizedOrigins.includes(origin)) {
callback(null, true);
} else {
callback( notAcceptable('Domain not allowed by CORS') );
}
},
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Accept', 'Content-Type', 'Authorization', 'Origin', 'From'],
credentials: true,
},
Swagger Options file
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'Nitin API',
version: '1.0.0',
description: 'NITIN API Documentation'
},
servers: [
{
url: 'http://localhost:8101/api/v1',
description: 'Local server'
},
{
url: 'https://vtt.myclient.com/api/v1',
description: 'DEV Env'
}
],
components: {
securitySchemes: {
JWTAuth: { // Define the Bearer Token (JWT) security scheme
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
}
},
security: [{
JWTAuth: []
}]
},
apis: ['src/api/core/routes/v1/*.ts'],
// apis: ['../core/routes/v1/*.ts']
};
const swaggerSpec = swaggerJsdoc(swaggerOptions);
// console.log("swaggerSpec", swaggerSpec);
const excludeSwagger = true;
if(excludeSwagger){
// this.application.use('/api-docs', (req, res, next) => {
// req.headers['Content-Type'] = CONTENT_TYPE_ENUM['application/json'];
// next();
// });
this.application.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}
the part where i might be getting this error
validate(req: Request, res: Response, next: (e?: Error) => void): void {
if (req.method === 'OPTIONS') {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': ['Content-Type', 'Authorization', 'Origin'],
'Access-Control-Allow-Methods': '*',
});
res.end();
return ;
}
if (!req.headers['content-type']) {
return next( notAcceptable(`Content-Type headers must be ${CONTENT_TYPE} or 'multipart/form-data', ${req.headers['content-type']} given`) );
}
const contentType = req.headers['content-type'];
if (['PATCH', 'POST', 'PUT'].includes(req.method)) {
if(CONTENT_TYPE_ENUM['text/plain'] === req.headers['content-type']) {
console.log('second')
return next( notAcceptable(`Content-Type headers must be ${CONTENT_TYPE} or 'multipart/form-data', ${req.headers['content-type']} given`) );
}
}
if ( CONTENT_TYPE_ENUM[CONTENT_TYPE] !== req.headers['content-type'] && req.headers['content-type'].lastIndexOf(CONTENT_TYPE_ENUM['multipart/form-data']) === -1 && CONTENT_TYPE_ENUM['text/plain'] !== req.headers['content-type'] && CONTENT_TYPE_ENUM['application/json; charset=utf-8'] !== req.headers['content-type']){
console.log('third')
console.log('req.headers', req.headers['content-type'])
// if(req.headers['content-type'] === 'text/plain'){
// console.log('fourth')
// }
return next( notAcceptable(`Content-Type head must be ${CONTENT_TYPE}, multipart/form-data or application/json; charset=utf-8, but ${req.headers['content-type']} given`) );
}
if (!req.headers.origin) {
return next( notAcceptable('Origin header must be specified') );
}
I tried to remove Headers hoping to resolve to something but didn't work quite frustrating maybe i am not able to get to the point which might be causing this issue.
if(req.method === 'GET'){
delete req.headers['content-type']
}
if (
req.headers['content-type'] &&
CONTENT_TYPE_ENUM[CONTENT_TYPE] !== req.headers['content-type'] &&
req.headers['content-type'].lastIndexOf(CONTENT_TYPE_ENUM['multipart/form-data']) === -1 &&
CONTENT_TYPE_ENUM['text/plain'] !== req.headers['content-type'] &&
CONTENT_TYPE_ENUM['application/json; charset=utf-8'] !== req.headers['content-type']
) {
console.log('third')
console.log('req.headers', req.headers['content-type'])
return next( notAcceptable(`Content-Type head must be ${CONTENT_TYPE}, multipart/form-data or application/json; charset=utf-8, but ${req.headers['content-type']} given`) );
}
Please ignore if i have done something stupid any help would be highly appreciated. Thanks!
you seem to be stuck on GET request you are trying to delete the headers but it won't help instead try to look for request method GET and put a condition to check if the headers don't receive content type application json then assign
req.headers['content-type'] = 'application/json';
this should solve your error.