如何在使用koa的react路由器中使用浏览器历史记录

How to use Browser history in react router with koa

本文关键字:浏览器 记录 路由器 历史 koa react      更新时间:2023-09-26

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

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

但在koa中,以下代码不起作用。当请求没有被koa路由器处理时,它将返回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')
  })
router.get('*', async function(ctx, next) {
  var html = fs.readFileSync(path.resolve('./build/index.html'));
  ctx.type = 'html';
  ctx.body = html;
})

这对我有效

从本质上讲,您想要实现的是服务器渲染。您需要使用match&路由器上下文。react-router对此有详细的文档。

反应路由器中的服务器渲染

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

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)

我在网上找到了几张看起来不错的回购单。不过我还没有核实。

布雷科枢纽

koa反应等分子量