除了 GET 之外,所有 API 都可以无缝运行。我无法解决的问题请帮助我解决这个问题。
/**
* @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);
当我点击这个时,我收到此错误
错误:::1 HTTP/1.1 500 GET /api/v1/admin/get_role_for_assigning - 无法读取未定义的属性“lastIndexOf”(#unknown): ServerError:无法读取未定义的属性“lastIndexOf” 在 Function.get (/home/cubix/vtt-backend/dist/api/core/factories/error.factory.js:31:28) 在工厂(/home/cubix/vtt-backend/dist/api/core/middlewares/catch.middleware.js:24:43) 在 Layer.handle_error (/home/cubix/vtt-backend/node_modules/express/lib/router/layer.js:71:5) 在trim_prefix(/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:321:13) 在/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:284:7 在 Function.process_params (/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:341:12) 接下来(/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:275:10) 在通知时(/home/cubix/vtt-backend/dist/api/core/middlewares/catch.middleware.js:21:9) 在 Layer.handle_error (/home/cubix/vtt-backend/node_modules/express/lib/router/layer.js:71:5) 在trim_prefix(/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:321:13) 在/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:284:7 在 Function.process_params (/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:341:12) 接下来(/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:275:10) 在 Layer.handle_error (/home/cubix/vtt-backend/node_modules/express/lib/router/layer.js:67:12) 在trim_prefix(/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:321:13) 在/home/cubix/vtt-backend/node_modules/express/lib/router/index.js:284:7
这就是cors的处理方式
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 选项文件
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));
}
我可能会遇到此错误的部分
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') );
}
我尝试删除标头,希望能够解决某些问题,但效果不佳,令人沮丧,也许我无法达到可能导致此问题的程度。
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`) );
}
如果我做了一些愚蠢的事情,请忽略任何帮助,我们将不胜感激。 谢谢!
您似乎陷入了 GET 请求,您正在尝试删除标头,但这无济于事,而是尝试查找请求方法 GET 并设置一个条件来检查标头是否未接收内容类型应用程序 json 然后进行分配
req.headers['content-type'] = 'application/json';
这应该可以解决您的错误。