概述
前端路由與后端路由的結合一直是一個難題。koa-static這個中間件能夠把靜態資源“搬到”后端路由上面去,react-create-app在不解構的情況下只會把資源打包到build文件夾,怎么協調koa-static,react-create-app和react-router-dom?我摸索出了一個解決方案,記錄下來,供以后開發時參考,相信對其他人也有用。
源碼可以參考我的github。
文件結構
我們的koa服務器的地址為:http://localhost:3000/
,文件結構如下:
├── controllers #后端
├── models #后端
├── routes #后端路由
├── node_modules
├── static #前端react文件夾
│ ├── build #react-create-app打包默認地址(需要先打包)
│ ├── node_modules
│ ├── public
│ ├── src
│ └── package.json等配置
│
├──app.js #后端啟動文件
└──package.json等配置
前端路由
前端路由是由react-router-dom控制的,我們需要創造一個中間路徑,我命名為react-blog,代碼如下:
<Router>
<Switch>
<Route path='/react-blog' component={Layout} />
<Redirect from='/' to='/react-blog'/>
</Switch>
</Router>
我們的目的是要把'/'路徑映射到'/react-blog'路徑,這樣react的靜態資源路由就不會影響到全局路由。
koa-static
koa-static這個中間件起一個映射的作用,它把被映射的文件夾全部映射到http://localhost:3000/
下面,我們關於koa-static這個中間件的代碼如下:
//app.js
//koaStatic
app.use(koaStatic(
path.join(__dirname, './static')
));
這樣就可以把static文件夾下的資源全部映射到http://localhost:3000/
下面,我們在瀏覽器中輸入如下地址則可訪問相應的文件。
//訪問前端react文件夾下的package.json文件
http://localhost:3000/package.json
//訪問前端react打包后的index文件
http://localhost:3000/build/index.html
這個時候我們能通過http://localhost:3000/build/index.html
訪問我們的react靜態資源,訪問的時候路由會自動交給前端路由,並且跳轉到http://localhost:3000/react-blog
這個地址。
但是當我們在另一個瀏覽器標簽里面輸入http://localhost:3000/react-blog
這個地址的時候,會返回404,原因是我們的后端路由並沒有react-blog這個選項,所以我們需要繼續配置后端路由。
koa-router
我們用koa-router另外開一個后端路由,來處理http://localhost:3000/react-blog
這個路徑,代碼如下:
//blog.js
const Router = require('koa-router');
let routerBlog = new Router();
routerBlog.get('*', async (ctx) => {
ctx.redirect('/build/index.html');
})
module.exports = routerBlog;
//router.js
const routerBlog = require('./blog');
let router = new Router();
router.use('/react-blog', routerBlog.routes(), routerBlog.allowedMethods());
module.exports = router;
上面的代碼把路徑http://localhost:3000/react-blog
下的所有路徑全部導向http://localhost:3000/build/index.html
,這樣它會自動跳轉到react靜態資源,並且把路由交給前端路由。
其它
上面就基本實現了前端路由和后端路由相結合。
但是還美中不足的是,所有指向前端靜態資源的url都會跳轉到前端靜態資源的主頁。這就造成了一個bug,就是我收藏了前端靜態資源其中的一個頁面,當我下次想打開這個頁面的時候只會跳到主頁,並不會跳到這個頁面。
這個bug留待后續優化了,思路是用正則截取后面的路徑,然后通過傳參傳給前端路由,再由前端路由處理。