在express中,我们可以只用下面的代码来处理请求。当请求未被路由器处理时,服务器端将发送 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')
})
最佳答案
router.get('*', async function(ctx, next) {
var html = fs.readFileSync(path.resolve('./build/index.html'));
ctx.type = 'html';
ctx.body = html;
})
这对我有用
关于javascript - 如何在带有koa的 react 路由器中使用浏览器历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38850981/