如何在koa的反应路由器中使用浏览器历史logging

在快递中,我们可以使用以下代码来处理请求。 当请求不是由路由器处理时,服务器端将发送index.html。

app.get('*', function (request, response){ response.sendFile(path.resolve(__dirname, '../public', 'index.html')) }) 

但是在koa中,以下代码不起作用。 当请求不被koa-router处理时,它将返回404而不是index.html。

 var send = require('koa-send') var serve = require('koa-static') var router = require('koa-router') var koa = require('koa') var app = koa(); app.use(serve(__dirname+'/../public')); app.use(function *(){ yield send(this, path.join(__dirname, '/../public/','index.html' )); }) app.use(router.routes()) 

以下代码也不起作用

 router .get('*', function* () { yield send(this, __dirname +'/../public/index.html') }) 

基本上你想要实现的是服务器渲染。 您需要使用match&RouterContext编写路由configuration。 react-router有详细的文档。

服务器在react-router上的渲染

在koa的情况下,大致可以这样做。

 import router from 'koa-router' import { match, RouterContext } from 'react-router' const koaRouter = router() const otherRouter = () => { return new Promise((resolve, reject) => { match({ routes, location }, (error, redirectLocation, renderProps) => { ... .. . } } koaRouter .use(otherRouter) 

我在网上发现了几个回购,看起来相当不错。 我还没有validation他们。

breko毂

KOA-反应-isomoprhic

 router.get('*', async function(ctx, next) { var html = fs.readFileSync(path.resolve('./build/index.html')); ctx.type = 'html'; ctx.body = html; }) 

这对我有用