zoukankan      html  css  js  c++  java
  • koa-static与react-create-app搭配的路径

    概述

    前端路由与后端路由的结合一直是一个难题。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留待后续优化了,思路是用正则截取后面的路径,然后通过传参传给前端路由,再由前端路由处理。

  • 相关阅读:
    ORA-01940: cannot drop a user that is currently connected解决方法
    Git基本用法简介
    C 入门 第十节 存储区
    C 入门 第九节 结构体指针
    C 入门 第八节 指针
    C 入门 第七节 结构体
    C 入门 第六节 自定义函数
    C 入门 第五节 多维数组 字符串数组
    C 入门 第四节
    C 入门 第三节
  • 原文地址:https://www.cnblogs.com/yangzhou33/p/9043785.html
Copyright © 2011-2022 走看看