【问题标题】:What is the difference between Routing in React and ExpressReact 和 Express 中的路由有什么区别
【发布时间】:2019-09-24 01:15:25
【问题描述】:

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

我的基本理解是 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 时,我无法理解这是如何变化的。

【问题讨论】:

    标签: reactjs express react-router express-router


    【解决方案1】:

    嗯,他们之间确实有区别。当您使用 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 这样的普通视图引擎, 把手然后在从 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 路由不同。 &lt; Route path="/about" component={About} /&gt;,可以给这个地址 您喜欢的任何东西,即"/details" 等。您只需提供与快速端点相同的axios.get(endpoint) 地址。但是你必须使用 react-router-dom 中的Link 才能到达快速路由的确切端点路径。

    &lt;Link to='/about'&gt;About&lt;/Link&gt; 应与app.get('/about',.....) 相同

    希望这能解决您在理解 react-router 和 express 路由方面的问题。

    【讨论】:

    • 这就是您所说的 - React 路由用于将组件映射到 URL,而 Express 路由是公开 REST API 端点以使用 HTTP 协议(​​GET、POST、PUT、DELETE )。当在前端命中路由时,它将呈现映射的组件,该组件将为所需的资源调用暴露的 REST API(例如来自数据库的 JSON 数据)
    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2021-11-09
    • 2020-11-06
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多