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

NestJS本地启动正常但浏览器连接被拒绝问题求助

NestJS应用本地启动正常但浏览器连接被拒绝问题排查

问题描述

我有一个已运行多年且已投入生产环境的NestJS应用,近期需要新增功能,该应用在本地机器启动正常,但浏览器访问时提示连接被拒绝。

附main.ts代码

import 'dotenv/config';
let appInsights = require("applicationinsights");
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import * as express from 'express';
import { join } from 'path';
import * as helmet from 'helmet';
import * as rateLimit from 'express-rate-limit';


appInsights.setup(process.env.azureAppInsight).start();

appInsights.defaultClient.addTelemetryProcessor((envelope, context) => {
  const httpRequest = context['http.ServerRequest'];
  const baseData = envelope.data.baseData;
  if (httpRequest && appInsights.Contracts.domainSupportsProperties(baseData)) {
    if (httpRequest.method === 'POST') {
      baseData.properties['bodyRequest'] = JSON.stringify(httpRequest.body);
    } else {

    }
  }
  return true;
});

const port = process.env.PORT;

async function bootstrap() {

  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  //logger: ['log', 'error', 'warn', 'debug', 'verbose']
  if (process.env.NODE_ENV == 'development') {
    const options = new DocumentBuilder().addBearerAuth()
      .setTitle('Sure')
      .setDescription('')
      .setVersion('1.0')
      .addTag('Secured')
      .build();

    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup('', app, document);
  }

  app.enableCors();
  app.use(helmet());

  await app.listen(port);
  Logger.log('info', `Server running on http://localhost:${port}`);
}
bootstrap();

相关截图

浏览器连接被拒绝提示
终端启动日志


排查与解决方案

  1. 确认端口配置有效性

    • 检查.env文件是否配置了PORT变量,若未配置,代码中port会为undefined,导致服务无法正常监听指定端口。
    • 修复:在.env中添加PORT=3000(或其他可用端口),或给代码中的port设置默认值:
      const port = process.env.PORT || 3000;
      
  2. 验证服务实际监听端口

    • 查看终端日志中Server running on http://localhost:${port}的输出,若显示undefined,说明环境变量未正确读取。
    • 用命令确认端口占用:Mac/Linux执行lsof -i :<端口号>,Windows执行netstat -ano | findstr :<端口号>。
  3. 检查防火墙与代理干扰

    • 临时关闭本地防火墙测试是否能连接。
    • 若使用VPN、代理工具,关闭后重试访问。
  4. 排查Helmet安全头冲突

    • 临时注释app.use(helmet()),重启服务测试,若恢复访问,再逐步配置Helmet的具体规则避免冲突。
  5. 显式配置CORS规则

    • 若前端访问地址不在默认CORS允许范围内,可显式配置:
      app.enableCors({
        origin: 'http://localhost:你的前端端口',
        credentials: true
      });
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:55:17