解决 NestJS 项目中接口跨域问题的三种方案

NestJs允许我们以非常直观的方式启用CORS支持。你可以全局启用它,也可以为特定的路由启用。下面让我们一步一步来看如何操作。

方法一:全局启用CORS
在你的 main.ts文件中,你可以在创建Nest应用时启用CORS:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

  // 启用CORS
  app.enableCors();

  await app.listen(3000);
}
bootstrap();

这将允许所有不同源的客户端请求,没有任何限制。对于某些情况来说,这可能太宽泛了,因为这样设定后,任何网站都可以访问你的服务。

如果你想限制特定的源能够访问服务,可以传入一个选项对象:

app.enableCors({
  origin: '<http://example.com>', // 只有来自 <http://example.com> 的请求才被允许
});

还可以传入更多的配置选项,例如允许的HTTP请求方法、响应中包含的头信息等。

方法二:为特定路由启用CORS
如果你只希望为特定的路由启用CORS,你可以在对应的Controller上使用 @UseCors装饰器。例如:

import { Controller, Get, UseCors } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  @UseCors({
    origin: '<http://example.com>',
  })
  findAll() {
    // ...
  }
}

这将确保只有在访问 /cats路由时,才会启用CORS,并且只有来自 http://example.com的请求可以访问。

方法三:使用中间件来自定义CORS
如果你需要进行更为复杂的CORS配置,或者你希望有完全的控制权,你可以使用 cors这个NPM包,它提供了丰富的配置选项。这个方法也适用于你想对某些路由使用不同的CORS策略的情况。

首先,你需要安装 cors:

npm install cors

然后,在你的代码中引入并使用它:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors';

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

  // 使用自定义CORS中间件
  app.use(cors({
    origin: '<http://my-mobile-app.com>',
    // 更多的配置选项...
  }));

  await app.listen(3000);
}
bootstrap();

这将允许你把 cors作为一个函数调用并传递配置对象,根据需要进行详细的配置。

高级配置
对于一些更高级的配置,NestJs允许直接传递CORS配置到 NestFactory的 create方法中。例如:

const app = await NestFactory.create(AppModule, {
  cors: {
    origin: '<http://example.com>',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    allowedHeaders: 'Content-Type, Accept',
    credentials: true,
  },
});

上面的配置中,我们指定了允许请求的方法、允许的请求头,以及是否允许携带凭证(如cookies)。

注意事项
安全性:在配置CORS时,不推荐使用通配符()来允许所有来源,因为这可能会使你的应用更容易受到跨站请求伪造(CSRF)或其他攻击。
环境配置:实际项目中,不同的环境(开发、测试、生产)可能需要不同的CORS设置。推荐将CORS设置存储在环境变量中,并根据当前的运行环境载入。

app.enableCors({
  origin: process.env.CORS_ORIGIN || '*', // 生产环境应指定具体的域名
  methods: process.env.CORS_METHODS || 'GET,HEAD,PUT,PATCH,POST,DELETE',
  allowedHeaders: process.env.CORS_HEADERS || 'Content-Type, Accept',
  credentials: process.env.CORS_CREDENTIALS === 'true', // 请确保实际字符串值是'true'或者'false'
});

测试: 一旦你配置了CORS,确保你进行了适当的测试,包括从不同的源发起请求,确保配置按预期工作。

所有评论(61)

  1. What’s up, I read your blog on a regular basis.
    Your story-telling sttle is awesome, keep upp the good work! https://Fortune-Glassi.Mystrikingly.com/

  2. I am extremely impressed with your writing skills as well as with the layout on your weblog.
    Is this a paid theme orr did you modify iit yourself?
    Anyway keep up the excellent quality writing, itt is rare to see a great blog
    like this one these days. https://glassi-Info.blogspot.com/2025/08/deposits-and-withdrawals-methods-in.html

  3. Everyne loves it whenn people get together and share thoughts.

    Great website, keep it up! https://Topdubaijobs.ae/employer/tonebet-casino

  4. Jerome说道:

    free casino cash no deposit usa, is online gambling allowed in australia and no deposit casino offers usa, or newest online casino australia

    Here is my blog post :: rouletsplay wheel (Jerome)

  5. goplayslots.Net说道:

    poker tournaments 2021 united states, gala bingo gift vouchers
    uk and no deposit free bonus spins usa aug, 28,2021,
    or best casino sign up offers uk

    Feel free to visit my blog :: goplayslots.Net

  6. Claudio说道:

    5dollar deposit all spins casino, Claudio, united states, best no deposit bonus casino usa and best slot sites usa 2021, or online casinos usa friendly

  7. Beryl说道:

    top online pokies and casinos united states information, free
    spins no deposit online casino australia and how to win casino growtopia
    (Beryl) free spins no deposit required united kingdom, or
    united states live casino

  8. Cliff说道:

    usa android casino bonus, casino jack milwaukee and best online
    casino united kingdom fast payouts, or gambling 2022 – Cliff, facts australia

  9. no deposit bonus free spins uk, australian online casino deposit bonus
    and Make Money Online With Google casino united
    statesn dollars, or united kingdom online pokies paypal

  10. online gambling sites How Old Do You Gotta Be To Get In The Casino the usa, casinos in ontario canada and united statesn real
    money casino, or no deposit bonus casino united states 2021

  11. Raymundo说道:

    promo code casino usa, crush it online casino accept usa and online real slots australia, or online casino from united states

    Check out my blog post; do you burn cards in blackjack (Raymundo)

  12. Manual说道:

    niederlande deutschland dfb pokal quoten wetten; Manual,

  13. Latosha说道:

    bonus wettanbieter

    Also visit my webpage; was heißt hc 0 7 5 2 bei basketball wetten (Latosha)

  14. tarakam.co说道:

    wettstrategien livewetten

    My site spanien – deutschland wettquoten (tarakam.co)

  15. Lourdes说道:

    bester online wettanbieter

    My web site; wett tipps über unter tore, Lourdes,

  16. strategie sportwetten

    Feel free to surf to my blog – pferderennen hannover wetten

  17. buchmacher vergleich

    Here is my website … deutsche wettseiten, https://www.bestthaicasino.com,

  18. die besten wett tipps heute

    Also visit my web site; bester wettanbieter Ohne oasis (colegioargentina.cl)

  19. Santiago说道:

    beste wett app österreich (Santiago) bonus wettanbieter

  20. deutschland wetten

    Also visit my website – Sportwetten Ohne Oasis

  21. strategien sportwetten

    Also visit my web blog: was bedeuten quoten bei wetten (Teatrodellebirre.it)

  22. live quotenvergleich

    Feel free to visit my page: Wetten Italien Deutschland

  23. Milan说道:

    beste wett tipp seite

    Feel free to surf to my site :: wettseiten ohne lugas (Milan)

  24. Barbra说道:

    größte wettanbieter wetten online deutschland (Barbra)

  25. mind vault说道:

    **mind vault**

    mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking

  26. Margart说道:

    wetten buchmacher [Margart]
    em spiele

  27. wetten auf unentschieden strategie

    Take a look at my web blog :: Sportwetten deutschland

  28. wettanbieter deutschland bonus

    Here is my blog … Wetten Dass Online Spielen

  29. Norris说道:

    buchmacher ohne limitierung

    Also visit my site – sportwetten österreich rechtslage – Norris

  30. Marilyn说道:

    sportwetten sichere tipps (Marilyn) bonus
    paypal

  31. sportwetten südamerika strategie

    my web blog; österreich Wetten – http://Www.alyunaniya.com,

  32. iromizban.ir说道:

    wett tipps über unter tore

    Look at my webpage; Sportwetten Bonus einzahlung (iromizban.ir)

  33. wettquoten vergleich

    my blog post … wetten österreich türkei (https://Fauesp.edu.br/)

  34. wette deutschland spanien

    Look at my web site: Pferderennen Meran Wetten

  35. bonus buchmacher说道:

    wette deutschland

    Feel free to surf to my homepage … bonus buchmacher

  36. Walker说道:

    vorhersagen sportwetten

    My homepage: esport buchmacher (Walker)

  37. Francesca说道:

    top sportwetten

    Visit my website: wettbüro lizenz (Francesca)

  38. wettanbieter ohne limit

    Also visit my webpage … Sicherste sportwetten Strategie
    (http://gratis-wetten.com)

  39. wonderful submit, very informative. I wonder why the opposite
    specialists of this sector do not realize this. You must
    proceed your writing. I am confident, you’ve a huge readers’ base already!

    My web page … Rivers casino schenectady Blackjack rules

  40. online sportwetten app

    Also visit my webpage … Wettquoten heute (mehedi.royalbd.my.Id)

  41. Rozella说道:

    kombiwetten vorhersagen

    Check out my blog post – buchmacher tipps (Rozella)

  42. Milan说道:

    Hi to every body, it’s my first pay a visit of this weblog; this weblog carries remarkable and truly good information in favor of readers.

    my homepage … is the ameristar casino still open (Milan)

  43. Lydia说道:

    sportwetten app schweiz (Lydia) strategie forum

  44. Dawna说道:

    schweizer sportwetten anbieter

    Feel free to visit my site wettanbieter (Dawna)

  45. der buchmacher说道:

    sportwetten startguthaben ohne einzahlung

    My web site: der buchmacher

  46. Jamila说道:

    handicap wetten bedeutung

    Also visit my web blog – buchmacher düsseldorf, Jamila,

  47. Alberta说道:

    alle wettanbieter im vergleich

    Take a look at my web site … sportwetten lizenz deutschland beantragen (Alberta)

  48. spanien deutschland wettquoten

    Visit my page … Buchmacher Mit paypal,
    https://Suntech-india.com,

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注