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

Angular与Lambda对接时遭遇CORS跨域问题求助

解决Angular调用Serverless Lambda API的CORS问题

问题核心

浏览器发送带自定义头(如Authorization)的POST请求时,会先发送OPTIONS预检请求,你的Lambda handler当前只处理了POST请求,未处理OPTIONS请求,导致预检响应缺少CORS头触发报错。另外,Access-Control-Allow-Origin: *和Access-Control-Allow-Credentials: true不能同时使用,这是CORS强制规则,Postman不做严格校验,但浏览器会拦截。

修复步骤

1. 在Lambda handler中处理OPTIONS请求

修改Lambda代码,优先处理OPTIONS预检请求,直接返回带合规CORS头的响应:

module.exports.handler = async (event) => {
  // 处理OPTIONS预检请求
  if (event.httpMethod === 'OPTIONS') {
    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': 'http://localhost:4200', // 开发环境指定具体域名,生产替换为实际业务域名
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Authorization, Content-Type', // 明确列出允许的头,比*更安全
        // 不需要携带cookie等凭证则删除此行
        // 'Access-Control-Allow-Credentials': true,
      },
      body: '',
    };
  }

  // 处理POST请求
  if (event.httpMethod === 'POST') {
    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': 'http://localhost:4200',
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Authorization, Content-Type',
        // 'Access-Control-Allow-Credentials': true,
      },
      body: JSON.stringify(
        {
          message: "This is protected!",
          input: event,
        },
        null,
        2
      ),
    };
  }

  // 其他请求方法返回405
  return {
    statusCode: 405,
    headers: {
      'Access-Control-Allow-Origin': 'http://localhost:4200',
    },
    body: JSON.stringify({ message: 'Method Not Allowed' }),
  };
};

2. 调整Angular请求(可选)

如果不需要携带凭证(如cookie),保持现有请求代码即可,注意去掉多余的await(http.post返回Observable而非Promise,无需await):

postTest() {
  const path = BASE_URL + '/test';
  console.log('Posting');
  this.http.post<any>(path, {
    'test': 'This is a test'
  }, {
    headers: {
      'Authorization': 'secretToken'
    }
  }).subscribe(data => {
    console.log('Response:', data);
  });
}

若必须携带凭证,需在请求中添加withCredentials: true,同时确保Lambda的Access-Control-Allow-Origin为具体域名而非*:

this.http.post<any>(path, { 'test': 'This is a test' }, {
  headers: { 'Authorization': 'secretToken' },
  withCredentials: true
})

3. 关键规则说明

  • 浏览器会对带自定义头、非简单方法的请求触发预检,必须确保OPTIONS请求的响应包含合规CORS头
  • Access-Control-Allow-Origin: *与Access-Control-Allow-Credentials: true不可共存,二选一调整

为什么Postman正常?

Postman不会自动发送OPTIONS预检请求,也不严格校验CORS头冲突规则,因此能正常获取响应,但浏览器会严格遵循CORS规范,导致表现差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:00:21