feat: allow root controller method allow all cors

This commit is contained in:
Innei
2021-12-20 17:02:51 +08:00
parent 6538906429
commit 4d4eaeb2b1
6 changed files with 47 additions and 5 deletions

View File

@@ -12,9 +12,6 @@
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.codeActionsOnSave": {
"source.organizeImports": true,
},
"material-icon-theme.activeIconPack": "nest",
"cSpell.words": [
"qaqdmin"

View File

@@ -4,6 +4,7 @@ import {
Get,
HttpCode,
Post,
UseInterceptors,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { InjectModel } from 'nestjs-typegoose'
@@ -11,6 +12,7 @@ import PKG from '../package.json'
import { Auth } from './common/decorator/auth.decorator'
import { HttpCache } from './common/decorator/cache.decorator'
import { IpLocation, IpRecord } from './common/decorator/ip.decorator'
import { AllowAllCorsInterceptor } from './common/interceptors/allow-all-cors.interceptor'
import { RedisKeys } from './constants/cache.constant'
import { OptionModel } from './modules/configs/configs.model'
import { CacheService } from './processors/cache/cache.service'
@@ -23,6 +25,8 @@ export class AppController {
@InjectModel(OptionModel)
private readonly optionModel: MongooseModel<OptionModel>,
) {}
@UseInterceptors(AllowAllCorsInterceptor)
@Get(['/', '/info'])
async appInfo() {
return {
@@ -35,6 +39,7 @@ export class AppController {
}
@Get('/ping')
@UseInterceptors(AllowAllCorsInterceptor)
ping(): 'pong' {
return 'pong'
}

View File

@@ -0,0 +1,39 @@
import {
CallHandler,
ExecutionContext,
NestInterceptor,
RequestMethod,
} from '@nestjs/common'
import { FastifyReply } from 'fastify'
export class AllowAllCorsInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler<any>) {
const handle = next.handle()
const response: FastifyReply<any> = context.switchToHttp().getResponse()
const allowedMethods = [
RequestMethod.GET,
RequestMethod.HEAD,
RequestMethod.PUT,
RequestMethod.PATCH,
RequestMethod.POST,
RequestMethod.DELETE,
]
const allowedHeaders = [
'Authorization',
'Origin',
'No-Cache',
'X-Requested-With',
'If-Modified-Since',
'Last-Modified',
'Cache-Control',
'Expires',
'Content-Type',
]
response.headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': allowedHeaders.join(','),
'Access-Control-Allow-Methods': allowedMethods.join(','),
'Access-Control-Max-Age': '86400',
})
return handle
}
}

View File

@@ -1,3 +1,4 @@
import './utils/global.util'
import './zx.global'
import './_bootstrap'
// organize-imports-ignore
import './bootstrap'

View File

@@ -43,7 +43,7 @@ export class NoteController {
private readonly countingService: CountingService,
) {}
@Get('latest')
@Get('/latest')
@ApiOperation({ summary: '获取最新发布一篇记录' })
@VisitDocument('Note')
async getLatestOne(@IsMaster() isMaster: boolean) {