

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用部署清单部署 Express 服务器
<a name="deploy-express-server"></a>

此示例说明了如何使用 Amplify Hosting 部署规范部署基本的 Express 服务器。您可以利用提供的部署清单来指定路由、计算资源和其他配置。

**先在本地设置 Express 服务器，然后再部署到 Amplify Hosting**

1. 为您的项目创建一个新目录并安装 Express 和 Typescript。

   ```
   mkdir express-app
   cd express-app
    
   # The following command will prompt you for information about your project
   npm init
    
   # Install express, typescript and types
   npm install express --save
   npm install typescript ts-node @types/node @types/express --save-dev
   ```

1. 在项目的根目录中添加一个包含以下内容的 `tsconfig.json` 文件。

   ```
   {
     "compilerOptions": {
       "target": "es6",
       "module": "commonjs",
       "outDir": "./dist",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true
     },
     "include": ["src/**/*.ts"],
     "exclude": ["node_modules"]
   }
   ```

1. 在项目根目录中创建一个名为 `src` 的目录。

1. 在 `src` 目录中创建 `index.ts` 文件。这将是启动 Express 服务器的应用程序的入口点。应将服务器配置为在端口 3000 上侦听。

   ```
   // src/index.ts
   import express from 'express';
    
   const app: express.Application = express();
   const port = 3000;
    
   app.use(express.text());
    
   app.listen(port, () => {
     console.log(`server is listening on ${port}`);
   });
    
   // Homepage
   app.get('/', (req: express.Request, res: express.Response) => {
     res.status(200).send("Hello World!");
   });
    
   // GET
   app.get('/get', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-get-header", "get-header-value").send("get-response-from-compute");
   });
    
   //POST
   app.post('/post', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-post-header", "post-header-value").send(req.body.toString());
   });
    
   //PUT
   app.put('/put', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-put-header", "put-header-value").send(req.body.toString());
   });
    
   //PATCH
   app.patch('/patch', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-patch-header", "patch-header-value").send(req.body.toString());
   });
    
   // Delete
   app.delete('/delete', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-delete-header", "delete-header-value").send();
   });
   ```

1. 在您的 `package.json` 文件中添加以下脚本。

   ```
   "scripts": {
     "start": "ts-node src/index.ts",
     "build": "tsc",
     "serve": "node dist/index.js"
   }
   ```

1. 在项目根目录中创建一个名为 `public` 的目录。然后使用以下内容创建名为 `hello-world.txt` 的文件。

   ```
   Hello world!
   ```

1. 在项目的根目录中添加一个包含以下内容的 `.gitignore` 文件。

   ```
   .amplify-hosting
   dist
   node_modules
   ```

**设置 Amplify 部署清单**

1. 在项目根目录中创建一个名为 `deploy-manifest.json` 的文件。

1. 复制并在 `deploy-manifest.json` 文件中粘贴以下清单。

   ```
   {
     "version": 1,
     "framework": { "name": "express", "version": "4.18.2" },
     "imageSettings": {
       "sizes": [
         100,
         200,
         1920
       ],
       "domains": [],
       "remotePatterns": [],
       "formats": [],
       "minimumCacheTTL": 60,
       "dangerouslyAllowSVG": false
     },
     "routes": [
       {
         "path": "/_amplify/image",
         "target": {
           "kind": "ImageOptimization",
           "cacheControl": "public, max-age=3600, immutable"
         }
       },
       {
         "path": "/*.*",
         "target": {
           "kind": "Static",
           "cacheControl": "public, max-age=2"
         },
         "fallback": {
           "kind": "Compute",
           "src": "default"
         }
       },
       {
         "path": "/*",
         "target": {
           "kind": "Compute",
           "src": "default"
         }
       }
     ],
     "computeResources": [
       {
         "name": "default",
         "runtime": "nodejs22.x",
         "entrypoint": "index.js"
       }
     ]
   }
   ```

   清单描述了 Amplify Hosting 应如何处理您的应用程序的部署。主要设置如下。
   + **version** – 表示您正在使用的部署规范的版本。
   + **framework** – 调整此设置以指定您的 Express 服务器设置。
   + **imageSettings** – 除非您正在处理图像优化，否则此部分对于 Express 服务器来说是可选选项。
   + **routes** – 这些路由对于将流量引导到应用程序的正确部分至关重要。`"kind": "Compute"` 路由将流量引导到您的服务器逻辑。
   + **computeResources** – 使用此部分来指定 Express 服务器的运行时和入口点。

接下来，设置一个构建后脚本，用于将已构建的应用程序构件移动到 `.amplify-hosting` 部署包中。目录结构符合 Amplify Hosting 部署规范。

**设置构建后脚本**

1. 在项目根目录中创建一个名为 `bin` 的目录。

1. 在 `postbuild.sh` 目录中创建一个名为 `bin` 的文件。将以下内容添加到 `postbuild.sh` 文件。

   ```
   #!/bin/bash
    
   rm -rf ./.amplify-hosting
    
   mkdir -p ./.amplify-hosting/compute
    
   cp -r ./dist ./.amplify-hosting/compute/default
   cp -r ./node_modules ./.amplify-hosting/compute/default/node_modules
    
   cp -r public ./.amplify-hosting/static
    
   cp deploy-manifest.json ./.amplify-hosting/deploy-manifest.json
   ```

1. 在 `package.json` 文件中添加 `postbuild` 脚本。文件应该呈现以下状态。

   ```
   "scripts": {
     "start": "ts-node src/index.ts",
     "build": "tsc",
     "serve": "node dist/index.js",
     "postbuild": "chmod +x bin/postbuild.sh && ./bin/postbuild.sh"
   }
   ```

1. 要构建应用程序，请运行以下命令。

   ```
   npm run build
   ```

1. （可选）调整您的 Express 路由。您可以修改部署清单中的路由，使其适合您的 Express 服务器。例如，如果 `public` 目录中没有任何静态资产，则可能只需要指向 Compute 的捕获所有路由 `"path": "/*"`。这取决于您的设置。

最终目录结构应如下所示。

```
express-app/
├── .amplify-hosting/
│   ├── compute/
│   │   └── default/
│   │       ├── node_modules/
│   │       └── index.js
│   ├── static/
│   │   └── hello.txt
│   └── deploy-manifest.json
├── bin/
│   ├── .amplify-hosting/
│   │   ├── compute/
│   │   │   └── default/
│   │   └── static/
│   └── postbuild.sh*
├── dist/
│   └── index.js
├── node_modules/
├── public/
│   └── hello.txt
├── src/
│   └── index.ts
├── deploy-manifest.json
├── package.json
├── package-lock.json
└── tsconfig.json
```

**部署服务器**

1. 将您的代码推送到您的 Git 存储库，然后将您的应用程序部署到 Amplify Hosting。

1. 将您的构建设置更新为指向 `baseDirectory` 到 `.amplify-hosting`，如下所示。在构建过程中，Amplify 将检测 `.amplify-hosting` 目录中的清单文件并按照配置部署您的 Express 服务器。

   ```
   version: 1
   frontend:
     phases:
       preBuild:
         commands:
           - nvm use 18
           - npm install
       build:
         commands:
           - npm run build
     artifacts:
       baseDirectory: .amplify-hosting
       files:
         - '**/*'
   ```

1. 要验证您的部署是否成功以及服务器是否正常运行，请通过 Amplify Hosting 提供的默认 URL 访问您的应用程序。