在 Firebase 上托管 Express/React 应用程序:Express API 调用 404

时间:2021-03-18 14:14:56

标签: reactjs firebase firebase-hosting

我在 Firebase 托管上托管了一个带有 Express 后端的 React 应用。 虽然本地版本的效果很好,但调用我的 Express API 会产生 404。

我的文件树的相关部分如下;

Project
 | - client // On deploy we use client/public as public folder
       | - public 
       |      | - index.html 
       | - src
       |      | - App.js // React app here
       |      | - Chat.js // Calls to API made here
       | - package.json
 | - firebase.json
 | - package.json
 | - server.js // Express API functions here

在我的组件 Chat.js 中,我进行了以下调用:

    fetch("/api/input", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.state),
    })
        .then(res => res.text())
        .then(
            res => { .... // get response from the API  

要将此调用从托管在 http://localhost:3000 的 React 应用重定向到本地托管在 :5000 的 Express 应用,我的 client/package.json 包括

  "proxy": "http://localhost:5000/",

事实上,当本地托管时,对“http://localhost:3000/api/input”的 POST 请求会产生预期的结果。

至于server.js,它包括以下内容:

const express = require('express');
...
var firebase = require("firebase");
const functions = require('firebase-functions')
...
const app = express();
const port = process.env.PORT || 5000;
...
app.post('/api/input', async (req, res, next) => { ... }) // Here's the relevant API call
...
exports.app = functions.https.onRequest(app) // export to firebase functions ('app')

那么,firebase.json 如下:

{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "hosting": {
    "public": "client/build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/",
        "destination": "/index.html"
      },
      {
        "source": "/api/**",
        "function": "app" //should make sure that calls to the API are getting to the Express app
      }
    ]
  }
}

使用 firebase deploy 部署站点时,对 /api/input 的调用会产生: enter image description here

enter image description here

我可能遗漏了哪些阻止 API 调用到达我的 Express API 的步骤?

(我可以想象的是,firebase deploy 只部署构建的前端,但不知道如何解决)

2 个答案:

答案 0 :(得分:0)

您可能会忘记用于生产的配置。在您的服务器端 app.js 中

const path = require('path')

path 位于节点核心内部,因此您无需安装。

if(process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))

app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}

答案 1 :(得分:0)

Firebase 不支持 nodejs+express 应用。

它主要托管静态内容;为了运行server code you will want to look into cloud functions.