同时部署 Node.js Restfull API 和 Vue.js 应用程序

Deploy Node.js Restfull API and Vue.js app at the same time

我想在同一个项目中部署 Node.js express API 和 Vue.js 应用程序与 Vercel。

我的根文件夹中有一个 Vue.js 应用程序,我的根文件夹中还有另一个文件夹,例如 ./api

我在我的 package.json 文件中尝试了这个脚本(在我的 Vue.js 应用程序中):

"serve": "vue-cli-service serve && cd api && npm run start".

这是我的 Node.js 应用的 package.json 脚本:

"start": "node index.js"

但它不起作用。 (我知道“为什么它不起作用”的原因。)

如何在同一个项目中部署这两个应用程序?

(所以我想要一个 API 像这样的作品:example.com/api/urls

Vercel 是一个无服务器平台,而您对 Express 的使用是“有状态的”,这意味着您启动一个长 运行 服务器进程来侦听请求。另一方面,无服务器由短 运行 进程组成,这些进程根据需要产生以处理请求。

查看此指南以了解如何将 Express 与 Vercel 结合使用:https://vercel.com/guides/using-express-with-vercel

最简单的解决方案是将整个 Express 应用放入一个无服务器函数中(尽管这是一种反模式):

// /api/index.js

const app = require('express')()
const { v4 } = require('uuid')

app.get('/api', (req, res) => {
  const path = `/api/item/${v4()}`
  res.setHeader('Content-Type', 'text/html')
  res.setHeader('Cache-Control', 's-max-age=1, stale-while-revalidate')
  res.end(`Hello! Go to item: <a href="${path}">${path}</a>`)
})

app.get('/api/item/:slug', (req, res) => {
  const { slug } = req.params
  res.end(`Item: ${slug}`)
})

module.exports = app

并确保在 vercel.json:

中设置重写
{
  "rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}

(这些代码片段直接取自上面链接的指南——我强烈建议遵循它!)

更好的无服务器方法是将您的 Express 路由拆分为它们自己的可按需调用的无服务器函数。


此外,启动 API 的“服务”脚本是不必要的,因为 top-level API directory is zero-config with Vercel。您可以简单地使用 "serve": "vue-cli-service serve".