顯示具有 react 標籤的文章。 顯示所有文章
顯示具有 react 標籤的文章。 顯示所有文章

2023-03-26

將 React app 和 Node.js 寫的 API 放在同一台伺服器

將 React app 和 Node.js 寫的 API 放在同一台伺服器

要前後端分離,同時要將 React app 和 API 放在同一台伺服器相同的 port,以避免誇來源的問題。

此時可以用一台 Node express server 解決。

React app 發佈至 Express server 靜態資料夾

第一種方式是,把發佈後的 React 放在 build 資料夾(別的名稱也可以),並將 build 設定為靜態資料夾。

其餘後端的 API 可以定義在服務靜態 html 檔之前。

const express = require("express"); const fs = require("fs/promises"); const app = express(); app.use(express.static("build")); let html = ""; fs.readFile(__dirname + "/build/index.html").then((txt) => { html = txt.toString(); }); // app.use('/api', YOUR_ROUTER); // 可以把 api 掛在這裡 app.use("/api", (req, res) => { res.json({ name: "shinder", say: "hello" }); }); app.use((req, res) => { res.send(html); }); const port = 3005; app.listen(port, () => { console.log(`啟動 ${port}`); });

使用反向代理伺服器

另一種做法是使用反向代理伺服器,可以利用 http-proxy-middleware 套件,建立 proxy。

const express = require("express"); const { createProxyMiddleware } = require("http-proxy-middleware"); const app = express(); app.use(express.static("build")); // app.use('/api', YOUR_ROUTER); // 可以把 api 掛在這裡 app.use("/api", (req, res) => { res.json({ name: "shinder", say: "hello" }); }); app.use( "/", createProxyMiddleware({ target: "http://localhost:3000", changeOrigin: true, }) ); const port = 3005; app.listen(port, () => { console.log(`啟動 ${port}`); });

2018-06-04

跨埠存取 cross ports

筆記:
  一台主機同時跑 apache/php (port: 80) 和 node/express/react (port: 3000)
  react 要呼叫 php api 時,同時要傳遞 cookie 的情況
  1. apache/php 的 Access-Control-Allow-Origin 要指定,不可以是 wildcard (*)。
  2. apache/php 的 Access-Control-Allow-Credentials 設定為 true。
  3. react 發 ajax 時,withCredentials要設定為 true。

FB 留言