我使用Firebase Hosting构建REST API,但我遇到了URL路由问题。
这是一个很好的例子:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as express from 'express';
admin.initializeApp(functions.config().firebase)
const app = express();
// /user
export const user = functions.https.onRequest(async (req, res) => {
res.setHeader('Content-Type', 'application/json');
console.log("app", app)
return res.send({
name: "Leon",
age: 23
})
});
/用户回复: { 名称:" Leon", 年龄:23岁 }
这是我使用express进行动态URL路由的示例: Example resource
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as express from 'express';
admin.initializeApp(functions.config().firebase)
const app = express();
app.get('/', (req, res) => {
res.send('Root page');
});
app.get('/second', (req, res) => {
res.send('Sub function');
});
app.get('/hello/:name', (req, res) => {
res.send(`Hello ${req.params.name}`);
});
exports.route = functions.https.onRequest(app);
/ response =>错误:禁止 您的客户无权从此服务器获取URL /。
/ second response =>错误:禁止 您的客户端无权从此服务器获取URL /秒。
/ hello / johndoe response =>错误:禁止 您的客户端无权从此服务器获取URL / hello / johndoe。
答案 0 :(得分:0)
尝试使用Express中间件是cors。
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as express from 'express';
admin.initializeApp(functions.config().firebase)
const cors = require('cors')({origin: true});
const app = express();
app.use(cors);
app.get('/', (req, res) => {
res.send('Root page');
});
app.get('/second', (req, res) => {
res.send('Sub function');
});
app.get('/hello/:name', (req, res) => {
res.send(`Hello ${req.params.name}`);
});
exports.route = functions.https.onRequest(app);
答案 1 :(得分:0)
必须在您的GCP控制台上解决。只需执行以下步骤: