我很难理解前端路由和后端路由之间的区别。
我的基本理解是,React路由器将将组件映射到URL,如下所示:
<Router>
<div>
<Header />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>而Express-路由器将将html页面映射到特定的路由。
// GET method route
app.get('/', function (req, res) {
res.render('index.html')
})
// POST method route
app.post('/', function (req, res) {
res.redirect('/')
})我一直认为前端负责创建视图,后端会将这些视图映射到一个路径。这意味着访问一个路由将呈现相关的模板。
当使用React路由和Express-路由器时,我无法理解这是如何改变的。
发布于 2019-05-06 19:15:33
嗯,他们之间确实有区别。当您使用react路由器时,您可以使用路由器和链接组件来呈现有关组件,这将向您发送关于页面链接的。
<Link to='/about'>About</Link>
< Route path="/about" component={About} />在express中,如果您呈现这样的视图,情况也是一样的:
app.get('/about', function (req, res) {
res.render('about.html')
})让我们看看,你想要你的数据库数据在前端。如果您使用诸如ejs、工具栏之类的普通视图引擎,那么在从db找到数据之后,您将将它们呈现为html或ejs页面。
如果您对单个页面应用程序使用react,那么您就不需要router路由器。但是如果你的应用程序有多个页面,那么使用react路由器是很好的。
参见下面的示例代码:
app.get('/about', function(req, res) {
// finding the user details from database
user.find()(function(err, users) {
if (err) {
console.log(err);
} else {
res.json(users); //sends the user data
}
});现在,React必须从后端抓取这些数据,它可以通过多种方法完成,我更喜欢使用axios包,它是npm做的与FETCH相同的工作。
axios.get('http://localhost:5000/about')
.then(response => {
this.setState({users: response.data}); //this reponse.data is coming from backend
})
.catch(function (error) {
console.log(error);
})所以现在,您可以看到react路由器-dom与快速路由不一样。< Route path="/about" component={About} />,您可以提供任何您喜欢的地址,例如,"/details"等。您只需给出与快递端点相同的axios.get(endpoint)地址。但是您必须使用Link,从router到快速路由的精确端点路径。
<Link to='/about'>About</Link>应与app.get('/about',.....)相同
希望,这将解决您的问题,了解反应-路由器和快速路由。
https://stackoverflow.com/questions/56004572
复制相似问题