GCF 目前不支持函数内的路由。因此,解决方案取决于用例,但对于大多数简单的情况,例如问题中的示例,编写一个简单的路由器是一种合理的方法,不涉及更改正常的请求格式。
如果涉及参数或通配符,请考虑使用route-parser。以deleted answer 建议this app 为例。
Express 请求对象有一些您可以利用的有用参数:
-
req.method 给出 HTTP 动词
-
req.path 给出不带查询字符串的路径
-
req.query解析后的key-value查询字符串的对象
-
req.body 解析后的 JSON 正文
这里有一个简单的概念证明来说明:
const routes = {
GET: {
"/": (req, res) => {
const name = (req.query.name || "world");
res.send(`<!DOCTYPE html>
<html lang="en"><body><h1>
hello ${name.replace(/[\W\s]/g, "")}
</h1></body></html>
`);
},
},
POST: {
"/user/add": (req, res) => { // TODO stub
res.json({
message: "user added",
user: req.body.user
});
},
"/user/remove": (req, res) => { // TODO stub
res.json({message: "user removed"});
},
},
};
exports.example = (req, res) => {
if (routes[req.method] && routes[req.method][req.path]) {
return routes[req.method][req.path](req, res);
}
res.status(404).send({
error: `${req.method}: '${req.path}' not found`
});
};
用法:
$ curl https://us-east1-foo-1234.cloudfunctions.net/example?name=bob
<!DOCTYPE html>
<html lang="en"><body><h1>
hello bob
</h1></body></html>
$ curl -X POST -H "Content-Type: application/json" --data '{"user": "bob"}' \
> https://us-east1-foo-1234.cloudfunctions.net/example/user/add
{"message":"user added","user":"bob"}
如果您遇到 CORS 和/或预检问题,请参阅 Google Cloud Functions enable CORS?