如何在使用koa的react路由器中使用浏览器历史记录
How to use Browser history in react router with koa
在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反应等分子量
相关文章:
- 浏览器何时记录历史记录
- Angular JS-如何强制浏览器记录历史以便快速路由
- 将HTML表单发布到iframe会导致浏览器历史记录出现问题
- 如何防止浏览器在历史记录中缓存HTML
- 如何在不使用插件的情况下用程序记录浏览器操作
- 检查浏览器后退按钮历史记录
- 制作一个阻止存储在浏览器历史记录中的网页
- 使用服务器路由响应路由器浏览器历史记录
- JS函数在浏览器历史记录中返回特定域的上次浏览页面
- 使jQuery scrollTop不离开浏览器历史记录
- React Router浏览器历史记录适用于本地,而不适用于生产
- jquery cookie,在清除浏览器历史记录后仍然设置
- 通过javascript从浏览器历史记录中删除URL
- 如何防止浏览器在浏览浏览器历史记录时卡在Angular路线上
- 使用Backbone.js处理浏览器历史记录
- 使用javascript获取浏览器历史记录,并通过php打印
- 我们可以使用Javascript获取浏览器历史记录吗
- 通过javascript访问浏览器历史记录,以实现自定义的后退和前进按钮
- 如何操作浏览器历史记录并捕获浏览器后退/前进按钮
- AppEngine:从浏览器记录事件(JavaScript)