如何判断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
相关产品推荐
相关产品推荐

