ZEIT Now 无服务器函数 - 带参数的路由

ZEIT Now Serverless Functions - Routes with Parameters

我创建了 4 个无服务器路由

我将它们包含在 api/now.json 文件中,如下所示:

{"src": "/api/list", "dest": "./list.js", "methods": ["GET"]},
{"src": "/api/add", "dest": "./add.js", "methods": ["POST"]},
{"src": "/api/update/*", "dest": "./update.js", "methods": ["PUT"]},
{"src": "/api/remove/*", "dest": "./remove.js", "methods": ["DELETE"]}

不使用参数的/api/list和/api/add路由可以工作,但是/api/update和/api/remove不工作,因为我可能没有在上面引用的 now.json 文件的 api 路径上正确使用正则表达式。

路由器的处理程序如下所示(仅相关路径)

app.put('/api/update/:id', (req, res) => {
  ...
});
module.exports = app;

src是你要匹配的传入请求路径,dest是应该执行的文件。

这意味着前两个不需要任何路由,因为访问 /api/list 将执行文件中的函数 /api/list.js,而 /api/add 将执行 /api/add.js .

您可以在 now.json 文件中使用 rewrites 来定义类似于表达模式的路由:

{
  "rewrites": [
    { "source": "/update/:id", "destination": "/api/update" },
    { "source": "/remove/:id", "destination": "/api/remove" }
  ]
}

/api/remove.js 中的示例函数如下所示:

module.exports = (req, res) => {
  const { id } = req.query;
  res.send('Removing ID ' + id);
});

或者,您可以将文件命名为 /api/remove/[id].js,这样就根本不需要定义 rewrites 配置。这叫做Path Segments