我正在使用Firebase Hosting托管具有Express后端的React应用程序。当本地版本正常运行时,调用我的Express API会产生404错误。
我的文件树的相关部分如下:
在我的组件
为了将来自于托管在 http://localhost:3000 的 React 应用的调用重新定向到本地托管在 :5000 的 Express 应用,我的
使用
可能有哪些步骤导致API无法到达我的Express API?
(我可以想象firebase deploy只部署了构建好的前端,但不确定该如何解决)
我的文件树的相关部分如下:
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](https://istack.dev59.com/kHAxf.webp)
![enter image description here](https://istack.dev59.com/Uiysg.webp)