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

如何判断Serverless Offline的Lambda API触发来源是本地还是服务器?

Serverless Offline 本地/服务器环境判断方案

自定义环境变量

在你的serverless.yml里配置专属环境变量:

provider:
  environment:
    IS_LOCAL: ${self:custom.isLocal}

custom:
  isLocal: ${env:IS_LOCAL, 'false'}

启动本地服务时带上变量:

IS_LOCAL=true sls offline

在Lambda函数里直接判断:

const isLocal = process.env.IS_LOCAL === 'true';
if (isLocal) {
  // 本地环境的处理逻辑
} else {
  // 线上服务器环境的逻辑
}

读取Serverless Offline专属请求头

Serverless Offline在本地触发请求时,会自动给请求加x-serverless-offline头,你可以从Lambda的event对象里读取这个头来判断:

exports.handler = async (event) => {
  const isLocal = !!event.headers['x-serverless-offline'];
  // 这里写对应的环境逻辑
};

通过请求Host判断

本地启动的服务一般用localhost或127.0.0.1,直接检查请求的host即可:

exports.handler = async (event) => {
  const isLocal = event.headers.host?.includes('localhost') || event.headers.host?.includes('127.0.0.1');
  // 执行对应逻辑
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:44:52