如何将所有服务器请求重定向到Firebase Hosting

时间:2018-04-27 23:13:22

标签: javascript firebase google-cloud-functions firebase-hosting

尝试使用Firebase实现SSR,因此我使用函数预呈现React App的每个页面。除了主页之外,它运行良好,因此它必须是firebase重定向上的匹配错误,或者可能是快速路由本身。

firebase.json

{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ]
  },
  "hosting": {
    "public": "build",
    "rewrites": [
      {
        "source": "**",
        "function": "contentServer"
      }
    ],
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

contentServer.js

import * as functions from 'firebase-functions';
import * as fs from 'fs';
import * as path from 'path';

import React from 'react';
import Helmet from 'react-helmet';
import { renderToString } from 'react-dom/server';
import Server from '../browser/Server.js';

const express = require('express');

const app = express();

// might be this? Also tried /**

app.get(['**'], (request, response) => {
  const context = {};
  const location = request.url;
  console.log('Processing request for ', location);

  let appCode;
  try {
    appCode = renderToString(<Server context={context} location={location} />);
  } catch (err) {
    appCode = 'with error';
  }

  // const appState = {
  //   pageTitle: 'Hello World',
  // };

  // const preloadedState = JSON.stringify(appState).replace(/</g, '\\u003c');
  const fileName = path.join(__dirname, '../index.html');
  const htmlTemplate = fs.readFileSync(fileName, 'utf8');
  const head = Helmet.renderStatic();

  const responseString = htmlTemplate
    .replace('<div id="root"></div>', `<div id="root">${appCode}</div>`)
    .replace('<title>React App</title>', `${head.title}\n${head.link}`);
  return response.send(responseString);
});

export default functions.https.onRequest(app);

卷曲

我运行firebase serve --only functions,hosting

然后使用curl检查响应:

curl http://localhost:5000 - does not render the home page - just the standard react page
curl http://localhost:5000/ - also does not work - just the standard react page.
curl http://localhost:5000/contact-us - works well and returns the contact us page, all other pages on the site work and trigger the function.

1 个答案:

答案 0 :(得分:4)

如果您想将主机中的每个网址重定向到云端功能中的快速应用,则需要执行以下操作:

确保您的公共托管文件夹中没有index.html(否则它将始终以路径/提供)。

在firebase.json中配置Firebase托管以重写函数的所有网址(您目前正在&#34;托管&#34;阻止,这很好):

"rewrites": [
  {
    "source": "**",
    "function": "contentServer"
  }
]

使用与重写中的函数相同的名称编写导出的云函数,并附加一个处理通配符*的快速应用程序。在函数文件夹的index.js中,最低限度:

const functions = require('firebase-functions')
const express = require('express')

const app = express()

app.get("*", (request, response) => {
    response.send("OK")
})

exports.contentServer = functions.https.onRequest(app)

如果您使用firebase serve --only hosting,functions在本地运行,则发送到localhost:5000的每个路径都会说&#34; OK&#34;。