3

我无法理解前端和后端路由之间的区别。

我的基本理解是 React-router 会将一个组件映射到一个 URL,例如:

   <Router>
      <div>
        <Header />

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/topics" component={Topics} />
      </div>
    </Router>

Express-router 会将 html 页面映射到特定路由

// GET method route
app.get('/', function (req, res) {
  res.render('index.html')
})

// POST method route
app.post('/', function (req, res) {
  res.redirect('/')
})

我一直认为前端负责创建视图,后端将这些视图映射到路由。这意味着访问路线将呈现关联的模板。

当使用 React-route 和 Express-router 时,我无法理解这是如何变化的。

4

1 回答 1

3

好吧,他们之间确实有区别。当您使用react-router时,您使用 Router 和 Link 组件来呈现about组件,该组件将向您发送about 页面链接。

<Link to='/about'>About</Link>
< Route path="/about" component={About} />

如果你渲染这样的视图,它在express中有点相同:

app.get('/about', function (req, res) {
  res.render('about.html')
})

让我们看看,您希望您的数据库数据在前端。如果您使用像 ejs、handlebars 这样的普通视图引擎,那么在从 db 中找到数据后,您会将它们呈现到 html 或 ejs 页面。

如果您将 react 用于单页应用程序,则不需要 react-router。但是如果你的应用有多个页面,那么使用 react-router 就很好。

请参阅下面的示例代码:

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 API 完成相同的工作。

 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-router-dom 与 express 路由不同。 < Route path="/about" component={About} />,你可以给这个地址任何你喜欢的东西,比如"/details"等等。你只需要给axios.get(endpoint)地址和快递端点一样的地址。但是您必须使用Linkfrom react-router-dom 才能到达快速路由的确切端点路径。

<Link to='/about'>About</Link>应该与app.get('/about',.....)

希望这能解决您关于理解 react-router 和 express 路由的问题。

于 2019-05-06T19:15:33.643 回答