我想使用Node.js在firebase宿主中分离/创建路由。我创建了两个JS文件:apiservice.JS和service.JS,它们包含firebase云函数。
apiservice.js文件包含与API请求相关的路由。services.js文件包含与正常使用请求相关的路由。当我运行此代码时,将出现以下错误:
无法获取/firebaseproject id/us-central1/app/api/
代码如下:
apiservice.js:
const functions = require('firebase-functions');
const express = require("express");
const app = express();
app.get("/api/login", (req, res) => {
//code
});
app.get("/api/signup", (req, res) => {
//code
});
exports.apiservice = functions.https.onRequest(app);
service.js:
const functions = require('firebase-functions');
const express = require("express");
const app = express();
app.get("/signup", (req, res) => {
//code
});
app.get("/login", (req, res) => {
//code
});
exports.service = functions.https.onRequest(app);
firebase.json:
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [{
"source": "/api",
"function": "apiservice"
},
{
"source": "/",
"function": "service"
}]
},
"functions": {
"predeploy": [
"npm --prefix "$RESOURCE_DIR" run lint"
]
}
}
任何帮助都将不胜感激。非常感谢。
我找到了一个解决方案。我没有在index.js文件中导入apiservice和service。因此,路由不起作用。所以,我稍微修改了一下代码,并在index.js文件中添加了几行。我从这里得到了参考:如何在Express中的多个文件中包含路由处理程序?
因此,更新后的工作代码是:
apiservice.js:
const functions = require('firebase-functions');
const express = require("express");
let apirouter = express.Router();
apirouter.get("/api/signup", (req, res) => {
//Code
});
module.exports = apirouter;
service.js:
const functions = require('firebase-functions');
const express = require("express");
let router = express.Router();
apirouter.get("/signup", (req, res) => {
//Code
});
module.exports = router;
index.js:
const functions = require('firebase-functions');
const express = require("express");
const apisrcrouter = require("./apiservice");
const srcrouter = require("./service");
let app = express();
app.get("/api/**", apisrcrouter);
app.get("/**", srcrouter);
module.exports = {
'apisrcrouter': functions.https.onRequest(apisrcrouter),
'srcrouter': functions.https.onRequest(srcrouter)
};
firebase.json:
{
"hosting": {
...
"rewrites": [
{
"source": "/api/**",
"function": "apisrcrouter"
},
{
"source": "/**",
"function": "srcrouter"
}]
...
}