❝随着一些云服务的发展与兴起,应用部署及上线的成本越来越低,甚至可以实现零成本部署。本系列文章将介绍如何使用薅羊毛的方式来搭建各个项目。 目前,首先更新在博客中,见: https://shanyue.tech/no-vps/ ❞
Vercel
,官网 https://vercel.com (opens new window)[1],如同 Netlify
一般,可以提供免费的前端应用托管,甚至对开发者更加亲和与友好。
以下截图,可见一斑: 「当你部署前端应用时,它能够根据你使用的技术栈而自动设置构建命令及输出目录」
使用vercel导入项目
Vercel
团队为了更好地推广他们的云服务,在开源中做了众多贡献,甚至盛名在外,以下几个 npm package 你即使没有使用过,但肯定会有所耳闻:
我们可以使用 Vercel
/Netlify
/AliOSS
以及各大云厂商的一些 Serverless 产品来几乎零成本地部署前端应用,但是偶尔也需要配套一些简单的 API 支持。如果购买一台云服务器,就是杀鸡焉用宰牛刀了。
你也可以选择各大云厂商的 Serverless 产品,但 Vercel
相对而言,学习成本低,更加容易上手,本篇文章介绍如何使用 Vercel
来部署 API 服务
新建 /api/index.js
,文件内容如下,标准的 HTTP Handler 的语法,只要你熟悉 http
模块,就可以很快上手:
module.exports = (req, res) => {
const { name = 'World' } = req.query
res.send(`Hello ${name}!`)
}
虽然很简单,但是也有可能出错,以下是源码及演示地址:
以上是使用 Node
作为运行时的代码,但其实它还可以使用以下编程语言:
Runtime 拥有更多的 API 及配置,可见文档:
Vercel Runtimes (opens new window)[7]
部署完成后,默认的路由路径是 /api
,此时 /
会显示文件目录,如果想更好地扩展路由呢?
通过配置文件 vercel.json
配置 Rewrites/Redirects
可完成此功能
{
"rewrites": [
{
"source": "/",
"destination": "/api"
}
]
}
由于 Vercel
这个 API 的本质也是 Serverless
,最适合做一些轻量的若存储的服务。我也收集了一些小而有创意的服务,如下所列
Original URL[12]
[1]
https://vercel.com (opens new window): https://vercel.com/
[2]
next.js (opens new window): https://github.com/vercel/next.js
[3]
swr (opens new window): https://github.com/vercel/swr
[4]
serve (opens new window): https://github.com/vercel/serve
[5]
https://github.com/shfshanyue/vercel-api (opens new window): https://github.com/shfshanyue/vercel-api
[6]
https://vercel-api-orpin-omega.vercel.app/api (opens new window): https://vercel-api-orpin-omega.vercel.app/api
[7]
Vercel Runtimes (opens new window): https://vercel.com/docs/runtimes#official-runtimes/node-js
[8]
github-readme-stats (opens new window): https://github.com/anuraghazra/github-readme-stats
[9]
shields.io (opens new window): https://github.com/badges/shields
[10]
qrcode api (opens new window): http://goqr.me/api/
[11]
imageproxy (opens new window): https://github.com/willnorris/imageproxy
[12]
Original URL: https://shanyue.tech/no-vps/api.html#hello-world