在 vercel 上的同一域上部署前端和后端

问题描述 投票:0回答:1

我正在使用 Express + Type 脚本作为后端。以及前端的 vite + React。 我想部署前端和后端以部署在 vercel 中的同一域中。支持cookies

项目结构

|- server
|    |- src/server.ts
|    |- package.json
|
|- client
|    |- src/
|    |- package.json
|
|- vercel.json

vercel.json

{
  "version": 2,
  "builds": [
    {
      "src": "server/src/server.ts",
      "use": "@vercel/node"
    },
    {
      "src": "client/package.json",
      "use": "@vercel/static-build",
      "config": {
        "distDir": "dist",
        "buildCommand": "npm run build"
      }
    }
  ],
  "rewrites": [
    {
      "source": "/api/(.*)",
      "destination": "server/src/server.ts"
    },
    {
      "source": "/(.*)",
      "destination": "client/dist/index.html"
    }
  ]
}

Vercel 部署映像

  • 它完美地构建了前端和后端,没有错误,但是前端和后端都不起作用,我的意思是无法访问。这是我的部署的网址:https://single-host.vercel.app。它只显示 404 错误。

部署域控制台日志

构建日志

vite v6.0.3 building for production...
transforming...
✓ 93 modules transformed.
rendering chunks...
computing gzip size...
dist/registerSW.js                0.13 kB
dist/manifest.webmanifest         0.33 kB
dist/index.html                   0.78 kB │ gzip:  0.40 kB
dist/assets/index-DOKYIi0D.css    0.88 kB │ gzip:  0.48 kB
dist/assets/index-5Zs-5n5D.js   214.14 kB │ gzip: 72.70 kB
✓ built in 2.67s
PWA v0.21.1
mode      generateSW
precache  6 entries (210.88 KiB)
files generated
  dist/sw.js
  dist/workbox-5ffe50d4.js
Installing dependencies...
up to date in 1s
23 packages are looking for funding
  run `npm fund` for details
Using TypeScript 5.7.2 (local user-provided)
Build Completed in /vercel/output [21s]
Deploying outputs...
Deployment completed
Uploading build cache [36.13 MB]...
Build cache uploaded: 607.56ms
deployment vercel
1个回答
0
投票

我怀疑您的初始 vercel.json 配置的问题是前端 (/) 的重写规则直接指向

client/dist/index.html
,它仅服务于根页面,不处理其他路由。 相反,您应该使用 /(.*) 作为前端重写规则中的源,以便所有路径(不仅仅是根路径)都正确路由到 client/dist 文件夹中的 React 应用程序的静态文件。

这是更正后的配置:

{
  "version": 2,
  "builds": [
    {
      "src": "server/src/server.ts",
      "use": "@vercel/node"
    },
    {
      "src": "client/package.json",
      "use": "@vercel/static-build",
      "config": {
        "distDir": "dist",
        "buildCommand": "npm run build"
      }
    }
  ],
  "rewrites": [
    {
      "source": "/api/(.*)",
      "destination": "server/src/server.ts"
    },
    {
      "source": "/(.*)",
      "destination": "client/dist/$1"
    }
  ]
}

此更新的配置可确保:

API 路由 (

/api/*
) 路由到 Express 后端。 所有其他路由 (
/(.*)
) 都正确路由到 React 前端,允许客户端路由处理
/about
/home
等路径。 这应该可以解决 404 错误并允许前端和后端在同一域上正常运行。

© www.soinside.com 2019 - 2024. All rights reserved.