[英]Using Create-React-App with Express in production
如何在生產模式下將我的react-app與express一起使用? 目前,我在一個終端中稱為yarn run start
,在另一個終端中稱為node server.js
。
在開發模式下,這很好用。 我在package.json( http:// localhost:8080 )中添加了"proxy"
。
問題是我不知道如何使它在實時模式下工作。 我只是稱其為yarn build
但是是的,服務器現在正在運行是沒有道理的;-)
我可以用簡單的方法解決嗎?
一些代碼:
package.json
"proxy": "http://localhost:8080"
server.js
const app = express();
app.post("/checkout", async (req, res) => {
...
});
app.listen(8080);
在react-app中,我使用axios將數據發布到此API。
我在開發模式下會獲得/想要的東西:
來自API的正確響應。
在生產模式下我想要什么:
來自API的正確響應。
我在生產模式下得到了什么:
錯誤:404(我認為是因為服務器未運行)
資料夾結構:
my-app
├── build
├── node_modules
├── public
│ ├── favicon.ico
│ ├── data
│ ├── index.html
│ └── manifest.json
├── scripts
│ ├── build.js
│ ├── start.js
├── src
│ ├── components
│ │ Component1.js, Component2.js, ...
│ ├── App.js
│ ├── index.css
│ ├── index.js
│ └── serviceWorker.js
├── .gitignore
├── package.json
├── server.js
└── README.md
我可以使用netlify的Lambda函數解決此問題嗎?
這是服務器腳本:server.js
const express = require("express");
const ... require(...);
const app = express();
app.post("/checkout", async (req, res) => {
console.log("Request:", req.body);
let error;
let status;
try {
const { token } = req.body;
const var1 = await stripe.customers.create({
...
});
const idempotency_key = uuid();
const charge = await stripe.charges.create(
{...}
);
}
res.json({ ... });
});
app.listen(8080);
其他方式:是否可以在php服務器上運行checkout api?
運行以下命令進行生產構建
npm run build
或yarn build
在server.js文件中添加以下行以將客戶端/構建作為靜態內容提供
app.use(express.static(path.join(__dirname, 'build')));
然后在定義的所有其他api路由的末尾添加以下路由,這將發送索引文件
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname,'build', 'index.html'));
});
客戶:
yarn build
是指yarn run build
。 yarn run
將執行package.json
scripts
部分中指定的命令。 在您的情況下,它將在scripts文件夾中運行build.js
文件。 通常,它將應用程序捆綁到靜態文件中以進行生產。 因此,現在必須提供正在生成的靜態文件。 該部分目前是客戶端。
{
"scripts": {
...
"build": "node scripts/build.js",
...
}
}
服務器:
我建議您使用serve-static
通過express
服務靜態文件。
yarn add serve-static
一起安裝yarn add serve-static
serverStatic(root,options)
,root將是包含靜態文件的目錄,否則默認情況下它將發送index.html
文件。 從文檔中可以很簡單地使用它:
var express = require('express') var serveStatic = require('serve-static') var app = express() app.use(serveStatic('public/ftp', { 'index': ['default.html', 'default.htm'] })) app.listen(3000)
您還可以在此處查看其他變體。
要在Heroku上部署項目,請遵循以下步驟 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.