Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

koa serves backend and SPA(with app-level router) at the same time #92

Open
NaClYen opened this issue Oct 4, 2022 · 0 comments
Open

Comments

@NaClYen
Copy link
Owner

NaClYen commented Oct 4, 2022

情境

期望使用 koa 框架讓SPA(React or Vue) 則使用如常, 但 api 占用 {host}/api/ 底下的網址.

一般配置的問題

常見的文章前後端共存, 都只是讓前端資訊視為一個靜態資源通通掛載在某個路徑底下

以下為我原本的配置(ESModule mode):

import koa from "koa";
import Router from "koa-router";
import bodyParser from "koa-bodyparser";
import serve from "koa-static";
import mount from "koa-mount";
import koaCors from "koa-cors";

// api 們
import api from "./api/index.mjs";

// ESModule 特殊處理
import * as url from "url";
import path from "path";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const getPath = (relPath) => path.resolve(__dirname, relPath);

const app = new koa();

// SPA
const webPage = new koa();
webPage.use(serve(getPath("../build"))); // 我的 SPA 放在上一層的資料夾中, 可替換至任何地方
app.use(mount("/", webPage));

// middlewares
app.use(bodyParser());
app.use(koaCors());

// routers
const appRouter = new Router();
appRouter.use("/api", api.routes(), api.allowedMethods());
app.use(appRouter.routes());

const PORT = process.env.PORT || 3456;
app.listen(PORT, () => {
  console.log(`Service on ${PORT}`);
});

問題

這樣是可以正常運作的, 只是 SPA 的 router 路徑會沒有反應
eg.
{host}/ -> {host}/config 這樣ok
但在 {host}/config 直接重整頁面, 就會直接 404...

原因

其實也蠻好理解的, koa 並沒有處理 SPA 的 router, 從 koa 的角度來看無法解析很正常.

秉持著我既然想過, 前人也一定都想過的信念
試過多種組合的關鍵字, 才終於在 Koa serve静态资源 看到一個相同的情境以及解決方式!

處理

我採用 koa2-connect-history-api-fallback

做法相當相當簡單:

...

// handle fallback for HTML5 history API
// 需要再 serve() 之前
app.use(historyApiFallback({ whiteList: ['/api'] }));

...
tags: nodejs react SPA koa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant