You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启用NestJS SWC后出现express-basic-auth非函数错误求助

解决NestJS启用SWC后express-basic-auth报错问题

启用SWC后出现TypeError: _expressbasicauth is not a function,核心原因是SWC对CommonJS模块的导入处理和tsc存在差异:express-basic-auth属于CommonJS模块,用* as expressBasicAuth导入时,实际的认证函数挂载在模块的default属性上,而非模块对象本身。

两种可行解决方式:

方式一:改用默认导入

直接修改导入语句,将命名导入改为默认导入:

import expressBasicAuth from 'express-basic-auth';

后续直接使用expressBasicAuth({ ... })即可正常调用函数。

方式二:保留原导入,调用时访问default属性

如果不想调整导入语句,在使用认证中间件时显式访问default属性:

app.use(
  ['/docs'],
  expressBasicAuth.default({
    challenge: true,
    users: {
      [configService.getOrThrow('SWAGGER_USER')]:
        configService.getOrThrow('SWAGGER_PASSWORD'),
    },
  }),
);

修改后的完整代码示例(方式一):

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as serveStatic from 'serve-static';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as cookieParser from 'cookie-parser';
import { Logger } from '@nestjs/common';
import expressBasicAuth from 'express-basic-auth';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);

  app.enableCors({
    origin: '*',
    preflightContinue: false,
    credentials: true,
  });

  app.use(
    ['/docs'],
    expressBasicAuth({
      challenge: true,
      users: {
        [configService.getOrThrow('SWAGGER_USER')]:
          configService.getOrThrow('SWAGGER_PASSWORD'),
      },
    }),
  );

  const config = new DocumentBuilder()
    .setTitle('Pray-App')
    .setDescription('外包API文档')
    .setVersion('3.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('/docs', app, document);

  app.use('/image', serveStatic('image'));

  //Cookie设置
  app.use(cookieParser());

  const port = configService.getOrThrow('SERVER_PORT');

  await app.listen(port);
  Logger.log(`服务器已在端口${port}启动`);
}
bootstrap();

内容的提问来源于stack exchange,提问作者GK 7734

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 10:33:28