为什么我得到一个404错误时部署谷歌云NodeJS应用程序?



我正在Google Cloud Console中构建一个NodeJS/React应用程序。在vite-project目录下使用npm run预览时,应用可以正常运行。然而,当我尝试通过cd到Top_Level_Directory和运行gcloud应用程序部署部署,我得到一个错误404在部署URL。我猜问题是在我的app.yaml或文件夹结构。有人能找到错误吗?

文件夹结构:

  • Top_Level_Directory:
    
  • —package.json
    —package-lock.json
    —app.yaml
    —vite-project
    —node_modules
    —style.css
    —router.jsx
    —package.json
    —package-lock.json
    —main.jsx
    —index.html
    —home_page.jsx
    —favicon.svg
    —App.jsx
    —node_modules
    —dist
    —index.html
    -assets
    -index.bab0b7c5.css
    -index.6689790b.js
    -favicon.17e50649.svg
    

App.yaml:

# [START cloud_tasks_app_yaml]
runtime: nodejs14
# [START cloud_tasks_app_env_vars]
env: standard
# [END cloud_tasks_app_env_vars]
# Handlers for serving the index page.
handlers:
- url: /vite-project
static_dir: /vite-project
- url: /
static_files: index.html
upload: index.html
# [END cloud_tasks_app_yaml]

npm run preview依赖于npm run build首先运行用生成的静态资源填充dist文件夹。您的App.yaml中的static_dir应该指向这个dist目录,以便其中的文件可以被服务。

我建议彻底检查您的项目结构,将静态、生成和动态资产分开。

示例结构

—vite-project
—dist
—index.html
-assets
—node_modules
-public
-favicon.ico
-index.html
-manifest.json
-robots.txt
-src
—style.css
—router.jsx
—main.jsx
—home_page.jsx
—favicon.svg
—App.jsx
—package.json
—package-lock.json
—app.yaml

已解析:

在vite-project文件夹中编辑app.yaml如下:

# [START cloud_tasks_app_yaml]
runtime: nodejs14
# [START cloud_tasks_app_env_vars]
env: standard
# [END cloud_tasks_app_env_vars]
handlers:
# Serve all static files with urls ending with a file extension
- url: /(.*..+)$
static_files: dist/1
upload: dist/(.*..+)$
# catch all handler to index.html
- url: /.*
static_files: dist/index.html
upload: dist/index.html

然后从vite-project文件夹中运行cloud app deploy(以及任何npm命令)。