首页 文章

Koa w /客户端路由器

提问于
浏览
2

现在的情况:

前端: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的<Link>时,每个网页都会显示 . 每当我刷新页面或手动输入链接时 . 我找到了一个“未找到”页面 . 顺便说一下,没有服务器端渲染 . 如何让React-Router处理上面未指定的路由,即仅在客户端上?

2 回答

  • 1

    刷新页面时,服务器必须回复某些内容;在这种情况下,它需要响应 index.html ,以便客户端应用程序可以启动,然后React Router可以根据URL安装正确的组件 .

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

  • 3

    解决方案(基于上面的答案)

    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 . :)

相关问题