【问题标题】:Koa w/client side router带有客户端路由器的 Koa
【发布时间】:2016-01-09 06:40:32
【问题描述】:

目前情况:

前端:React & React-Router

后端:Koa

app.use(mount('/graphql', graphqlHTTP({ schema: schema })));
app.use(mount('/api', api));
app.use(serve(__dirname + '../../public')); //serves static index.html

当我在浏览器中点击 React Router 的 时,每个网页都会显示。 每当我刷新页面或手动输入链接时。我得到一个“未找到”页面。顺便说一下,这里没有服务器端渲染。如何让 React-Router 处理上面未指定的路由,即仅在客户端上?

【问题讨论】:

    标签: javascript reactjs react-router koa


    【解决方案1】:

    当页面刷新时,服务器必须响应 something;在这种情况下,它需要响应index.html,以便客户端应用程序可以启动,然后React Router可以根据URL挂载正确的组件。

    因此,在服务器端,您需要告诉 Koa 为尚未匹配任何其他路由的每个 URL 提供index.html

    【讨论】:

    • 这里是@BinaryMuse 所说stackoverflow.com/questions/33062215/…的示例
    • 这是 Express 服务器的一个很好的例子;我会为 Koa 发布一个,但我对它不是很熟悉。 :)
    • 谢谢,我工作;我把 express 的例子翻译成 koa。
    【解决方案2】:

    解决方案(根据上面的答案)

    import router from 'koa-router';
    import sendfile from 'koa-sendfile';
    //code to initialize router
    //...
    
    router.get('*', function* () {
        let stats = yield* sendfile.call(this, pathToIndexHtml));
    
         if (!this.status) this.throw(404)
    })
    

    Koa 现在为每条未指定的路由提供 index.html。 :)

    【讨论】:

    • sendfile 的根是什么?它是相对于 server.js 的位置吗?
    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2014-07-21
    • 2015-04-17
    • 1970-01-01
    相关资源
    最近更新 更多