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

NestJS代理/admin请求至Prisma Studio时API请求404问题求助

解决方案

问题根源是Prisma Studio前端硬编码了/api作为API请求路径,当通过/admin路径访问Studio时,这些/api请求不会经过你配置的/admin代理中间件,导致404。只需调整代理规则,让/api请求也转发到Prisma Studio服务即可解决。

修改代理配置与路由匹配

1. 更新proxy.middleware.ts

调整代理逻辑,同时处理/admin和/api路径的请求,按需重写路径:

// proxy.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';

@Injectable()
export class ProxyMiddleware implements NestMiddleware {
  private readonly proxy = createProxyMiddleware({
    target: 'http://localhost:5555',
    changeOrigin: true,
    pathRewrite: (path) => {
      // 对/admin开头的路径,移除前缀后转发到Prisma Studio
      if (path.startsWith('/admin')) {
        return path.replace(/^\/admin/, '');
      }
      // /api路径直接转发,无需修改
      return path;
    },
  });

  use(req: Request, res: Response, next: () => void) {
    this.proxy(req, res, next);
  }
}

2. 更新app.module.ts

让代理中间件同时匹配/admin和/api路由:

// app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ProxyMiddleware } from './proxy.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(ProxyMiddleware).forRoutes('admin', 'api');
  }
}

逻辑说明

  • 访问localhost:3333/admin时,请求会被转发到localhost:5555(自动移除/admin前缀),正常加载Prisma Studio页面。
  • 页面发起的/api请求会被中间件捕获,直接转发到localhost:5555/api,彻底解决404问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:33:24