如何在nestJS后端使用条件app.use()?

问题描述 投票:0回答:1

这就是我尝试将

helmet
添加到我的 NestJS 应用程序中的方式。另外我需要添加
graphqlUploadExpress
如何正确使用
usesUpload
条件来使用
helm
helm + upload

import { NestFactory } from '@nestjs/core'
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import helmet from 'helmet'

const upload = graphqlUploadExpress()

export const main = async (
  AppModule: unknown,
  usesUpload = false
) => {
  const app = await NestFactory.create(AppModule, options)
  app.use(usesUpload ? helm : helm, upload) // <-- I think, this is not correct
  await app.listen(3000)
}
javascript express nestjs
1个回答
0
投票

我认为你的三元陈述是错误的。语法在这里: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator

这是我个人会写的:

import { NestFactory } from '@nestjs/core'
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import helmet from 'helmet'

const upload = graphqlUploadExpress()

export const main = async (
  AppModule: unknown,
  usesUpload = false
) => {
  const app = await NestFactory.create(AppModule, options)
  usesUpload && app.use(helm, upload)
  await app.listen(3000)
}

我使用逻辑 AND 运算符而不是三元运算符

&&
,如果
usesUpload
参数为
true

,它将有条件地执行

逻辑与文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

© www.soinside.com 2019 - 2024. All rights reserved.