【发布时间】:2021-08-02 12:43:42
【问题描述】:
我目前正在使用 GCP Cloud Functions (nodejs) 开发无服务器应用程序。 在下面的代码中,我可以根据请求的方法分离行为,但是 不知道怎么获取path参数的id。
例如,如果我想检索一个用户,路径将是 /users/:id。 我想检索路径中的 id 并搜索数据库,但我被卡住了,因为我无法检索到 id。 (也可以放置和删除) 有人知道吗?
我以为我可以用 req.params.id 得到它,但我想不是......
import type {HttpFunction} from '@google-cloud/functions-framework/build/src/functions';
export const httpServer: HttpFunction = (req, res) => {
const path = req.path;
switch(path) {
case '/users' :
handleUsers(req, res);
break;
default:
res.status(200).send('Server is working');
}
};
const handleUsers: HttpFunction = (req, res) => {
if (req.method === 'GET') {
res.status(200).send('Listing users...');
} else if (req.method === 'POST') {
res.status(201).send('Creating User...')
} else if (req.method === 'PUT') {
res.status(201).send('Updating User...')
} else if (req.method === 'DELETE') {
res.status(201).send('Delating User...')
} else {
res.status(404);
}
}
export const helloWorld: HttpFunction = (req, res) => {
res.send('Hello, World');
};
还有一个问题。
例如,如果当前 swich 语句中的路径为“/users/1”,则不会调用 handleUsers。所以我们也想解决这个问题。
另外,未来可能会有类似“/users/1/hogehoge”这样的路径......
【问题讨论】:
标签: node.js typescript express google-cloud-functions