It has been 988 days since the last update, the content of the article may be outdated.

项目结构

在项目根目录下创建api文件夹,在api中创建index.*(例如index.php)的文件,则该文件会被尝试执行,如果将js文件直接放在根目录,则会被当作文本文件读取

如果不创建,则你需要手动输入文件名来访问api

例如

*.vercel.app/api/js

vercel会根据后缀名自动判断语言

下面给出了3种语言的api示例:

python

python
from http.server import BaseHTTPRequestHandler


class handler(BaseHTTPRequestHandler):

def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("API by python!".encode())
return

nodejs

plaintext
module.exports = OnRequest;

function OnRequest(request, response){
response.send("API by nodejs!");
response.end();
}

php

该语言需要配置文件

php
<?php
echo "API by php!";

配置文件

在根目录下创建 vercel.json文件

plaintext
```vercel.json```中即可:
```php
{
"functions": {
"api/index.php": {
"runtime": "vercel-php@0.3.1",
"excludeFiles": "{test/**}",
"memory": 256,
"maxDuration": 5
}
}
}

通过配置文件还可以自定义路由

例如下面的json代码指定使用 /api/python.py文件执行 /python路由的请求

python
{
"functions": {
"api/php.php": {
"runtime": "vercel-php@0.3.1",
"excludeFiles": "{test/**}",
"memory": 256,
"maxDuration": 5
}
},
"routes": [
{
"src": "/python",
"dest": "/api/python"
}
]
}

构建

你能看到这篇文章,说明你肯定对vercel有些了解了,因此这里不在介绍怎么上传。但是构建时还有一个注意点,下图红圈圈起来的地方选择 Other(默认值)不要修改

访问

通过*.vercel.app/api/js,即可访问js写的api,其它文件同理

如果访问 *.vercel.app/api/js/ ,则会访问/api/js/目录下的index文件,因此在本项目中会报错

访问 *.vercel.app/python 和访问 *.vercel.app/api/python 是完全相同的,因为json中已经定义了这个路由