【发布时间】:2019-07-31 12:54:19
【问题描述】:
我需要使用一个存储库(来自 Google Cloud)在 Google Cloud Functions 中部署多个函数,并在 NodeJS 中使用 Express。
有可能做到这一点吗?
我有两个不同的模块(结帐、客户)和一个索引:
checkout.js
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*
*
*/
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const checkout = express();
checkout.use(cors({
origin: '*'
}));
const PORT = 5555;
checkout.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const COMMENTS = [
{
id: 1,
firstName: 'John1',
lastName: 'Smith'
},
{
id: 2,
firstName: 'Jane',
lastName: 'Williams'
}
];
checkout.get('/comments', (req, res, next) => {
res.json(process.env.TEST || 33);
}, function (err, req, res, next) {
res.json(err);
});
checkout.get('/:commentId', (req, res, next) => {
res.json(COMMENTS.find(comment => comment.id === parseInt(req.params.commentId)));
});
module.exports = checkout;
customer.js
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*
*
*/
const express = require('express');
const cors = require('cors');
const customer = express();
customer.use(cors({
origin: '*'
}));
const PORT = 5555;
customer.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const USERS = [
{
id: 1,
firstName: 'John',
lastName: 'Smith'
},
{
id: 2,
firstName: 'Jane',
lastName: 'Williams'
}
];
customer.get('/users', (req, res, next) => {
res.json(USERS);
});
customer.get('/:userId', (req, res, next) => {
res.json(USERS.find(user => user.id === parseInt(req.params.userId)));
});
module.exports = customer;
如何在 inde.js 中导入这些模块?
如果我这样添加,函数不会返回响应:
const checkout = require('./checkout');
const customer = require('./customer');
module.require = {
checkout,
customer
};
【问题讨论】:
-
无论您如何导出内容,这都行不通。您无法在 Cloud Functions 中侦听端口。那部分是为你管理的。您可以部署的只是您的路线。
-
@DougStevenson 我如何为不同的谷歌云功能导出不同的路线?
标签: node.js express google-cloud-functions