在Firebase上托管Express/React应用:Express API调用返回404

4
我正在使用Firebase Hosting托管具有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只部署了构建好的前端,但不确定该如何解决)

app.post('/api/input') 应该改为 app.post('/input')。 - OmG3r
尝试过了...这里没有改变任何东西。在这种情况下,是什么导致了这种变化,我的本地托管应用程序随后在“fetch”时出现错误“代理错误:无法将请求/ api / input从localhost:3000代理到http:// localhost:5000 /(ECONNREFUSED)”。 - Teresa
在本地主机上,您应该请求 localhost:5000/input,而在 Firebase 上,您需要请求 guidedduckbot-fogccm.web.app/api/input。 - OmG3r
你的 Github 链接 https://github.com/margotr/duckbot 已经失效了。 - Yu Miao
真的,对不起,我在使用GitHub时遇到了一些问题。我暂时删除了链接。 - Teresa
显示剩余5条评论
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'))
})
}

似乎这并没有改变情况... - Teresa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接