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

Firebase Functions部署失败:SyntaxError异常与async函数关联排查

解决Firebase Functions部署时的Async函数语法错误

你遇到的这个SyntaxError: Unexpected token function问题,核心原因是你的Firebase Functions运行环境使用的Node.js版本不支持async/await语法,再加上代码里还有几个小细节需要调整。下面一步步帮你解决:

1. 指定兼容的Node.js运行时版本

Firebase Functions早期默认使用Node.js 6,而Node 6对async/await的支持并不完善,需要开启特定特性才能使用。我们需要明确指定一个原生支持async/await的Node版本(比如Node 14或16,需和firebase-functions版本兼容)。

修改package.json

在你的package.json中添加engines字段,并升级相关依赖到兼容版本:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14" // 可选择14/16,需与firebase-functions版本匹配
  },
  "dependencies": {
    "firebase-admin": "^11.0.1",
    "firebase-functions": "^3.23.0",
    "google-auth-library": "^8.7.0",
    "nodemailer": "^6.8.0"
  },
  "devDependencies": {
    "eslint": "^8.26.0",
    "eslint-plugin-promise": "^6.1.1"
  },
  "private": true
}

修改后记得运行npm install,安装新版本的依赖包。

2. 修复代码中的语法与逻辑问题

你的代码里还有两个需要修正的点:

  • 内部getJwt函数里的res变量和外部onRequest的res重名,会导致变量覆盖
  • 调用async函数时未处理Promise,可能引发未捕获的异常

修改后的index.js代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const { JWT } = require('google-auth-library');

exports.sendContactEmailOAuth = functions.https.onRequest(async (req, res) => {
  const sender_msg = 'just a test';
  const email = 'contact@lechorodescharentes.org';

  async function getJwt() {
    const client = new JWT(
      functions.config().service_key.client_email,
      null,
      functions.config().service_key.private_key,
      ['https://www.googleapis.com/auth/cloud-platform', 'https://mail.google.com'],
    );
    await client.authorize();
    const url = `https://www.googleapis.com/dns/v1/projects/${functions.config().service_key.project_id}`;
    const response = await client.request({ url }); // 重命名变量避免冲突
    console.log(response.data);
    return response;
  }

  try {
    await getJwt(); // 用await处理async函数的Promise
    // 在这里添加nodemailer发送邮件的逻辑
    res.status(200).send('Request processed successfully');
  } catch (error) {
    console.error('Processing error:', error);
    res.status(500).send('Internal server error');
  }
});

3. 重新部署函数

完成以上修改后,运行以下命令重新部署:

npm install
firebase deploy --only functions

这样就能解决部署时的语法错误问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:33:42