GCP部署Node.js应用遇npm错误:Cannot read prop 'express' of undefined求助
问题:部署Google App Engine时出现
npm ERR! Cannot read property 'express' of undefined错误 操作步骤
- 创建项目
- 打开编辑器
- 创建名为"app1"的文件夹
- 将app.yaml、index.js和package.json文件放入"app1"文件夹中
- 打开编辑器底部的终端
- 执行
cd app1命令进入"app1"文件夹 - 执行
npm install命令 - 执行
gcloud app deploy命令
错误信息
文件上传完成。
更新服务[default]...失败。
ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build 38fc58ae-73c4-426c-b363-118df7ca4cf3 status: FAILURE
npm ERR! Cannot read property 'express' of undefined
相关文件代码
index.js
const express = require('express'); const app = express(); app.get('/', (req, res) => { const name = process.env.NAME || 'World'; res.send(`Hello ${name}!`); }); const port = parseInt(process.env.PORT) || 8080; app.listen(port, () => { console.log(`helloworld: listening on port ${port}`); });
package.json
{ "name": "helloworld", "description": "Simple hello world sample in Node", "version": "1.0.0", "private": true, "main": "index.js", "scripts": { "start": "node index.js" }, "engines": { "node": ">=12.0.0" }, "author": "Google LLC", "license": "Apache-2.0", "dependencies": { "express": "^4.17.1" } }
app.yaml
runtime: nodejs14 env: standard instance_class: F1
解决方案
检查本地依赖安装状态
确认本地执行npm install后,node_modules文件夹已生成且包含express包。若本地安装失败,先解决本地依赖问题再重新部署。清理缓存后重装依赖
在app1目录下依次执行:npm cache clean --force rm -rf node_modules package-lock.json npm install完成后重新执行
gcloud app deploy。对齐Node.js版本要求
将package.json中engines.node字段改为14.x,与app.yaml指定的nodejs14运行时版本完全匹配,避免版本兼容问题。配置忽略文件避免依赖冲突
创建.gcloudignore文件,内容如下,防止本地依赖被上传至构建环境:node_modules/ package-lock.json强制触发全新构建
执行gcloud app deploy --quiet,跳过缓存直接启动全新构建流程。
内容的提问来源于stack exchange,提问作者EmilyJ
相关产品推荐
相关产品推荐

