我使用 Firebase 托管和 Firebase 功能。
我希望两者都可以从同一个域访问:
HOSTING: https://xxxxxxxxx-dev.web.app/
FUNCTIONS: https://xxxxxxxxx-dev.web.app/app
根据文档我得到了这个:
index.ts(Firebase 函数)
const express = require('express');
const app = express();
// etc...
app.use(cors);
app.use(cookieParser(MY_SECRET_VALUE));
app.use(validateFirebaseIdToken);
app.post('/createPromo', async (req: any, res: any) => {
// etc...
res.json({ success: true, error: null, data });
});
exports.app = functions.https.onRequest(app);
firebase.json(在反应应用程序中)
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "/app",
"function": "app"
},
{
"source": "**",
"destination": "/index.html"
}
]
}
}
api.js(在React应用程序中)
const response = await fetch(`https://xxxxxxxxx-dev.web.app/api/createPromo`, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify(body)
});
当我从应用程序调用此端点时,我得到一个包含以下文本的 HTML 文件:
You need to enable JavaScript to run this app.
我从日志中可以看到 firebase 函数从未被触发。
如果我写的是
"source": "/app"
而不是"source": "/app/**"
,我得到了404错误未找到。
如果我从原始域调用该函数
https://us-central1-xxxxxxxxx-dev.cloudfunctions.net
,它就可以工作
我该如何解决这个问题?
您的快速路由需要与 URL 中的完整路径匹配,无论您的托管配置是什么。这意味着您需要包含“/app”前缀。
app.post('/app/createPromo', ...)