内容简介:先上react App代码点击后可以正常跳转至lottery路由,忽略丑陋的界面...
问题
先上react App代码
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
<Link to="/lottery">to lottery</Link>
<Route path="/lottery" component={Lottery} exact />
<Route path="/a" render={() => <div>in a</div>} exact />
</div>
</BrowserRouter>
)
}
}
点击后可以正常跳转至lottery路由,忽略丑陋的界面...
这时刷新就404找不到页面了
原因
react的BrowserRouter用的是Html5提供的HistoryApi方法,Link组件实际上是调用了History.pushState(),然后通过监听history状态去展示或者隐藏组件。所以当刷新时,也就是向服务器发送了这个路径的请求,而服务器上实际是没有对这个路径的请求做任何处理的,故返回的是404。
解决方法 -- 用的是koa搭建服务器
app.use(views(path.resolve(__dirname, '../www/dist'), {extension: 'html'}))
app.use(async (ctx, next) => {
console.log(ctx.path)
await next()
})
app.use(router.routes())
router.all(/\.js/i, static(path.resolve(__dirname, '../www/dist')))
router.all('*', async ctx => {
await ctx.render('index')
})
只要不是以.js结束的路由请求都返回index.html,js类型的就从项目打包出来的静态资源里找,相当于把路由的控制权交给了前端。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Python编程实战
[美] Mark Summerfield / 爱飞翔 / 机械工业出版社 / 2014-8 / 69.00元
《python编程实战:运用设计模式、并发和程序库创建高质量程序》由python开发者社区知名技术专家mark summerfield亲笔撰写,全球资深python专家doug hellmann作序鼎力推荐,是python领域最有影响力的著作之一。书中通过大量实用的范例代码和三个完整的案例研究,全面而系统地讲解了如何运用设计模式来规划代码结构,如何通过并发与cython等技术提升代码执行速度,以及......一起来看看 《Python编程实战》 这本书的介绍吧!