Routing

From CSE330 Wiki
Jump to navigationJump to search

You are not required to use Routing in this assignment, however, if you were going to build a full-stack web app, knowing how to use route is always nice.

Routing is how Web API matches a URI to an action. A key difference between PHP and web frameworks is in how routing occurs.

In PHP, if you went to an address like http://www.example.com/welcome.php then Apache would run the script located at, for example, /var/www/html/welcome.php.

However, frameworks do not generally work the same way. This is in part because of the MVC architecture. Most frameworks use a router instead that routes arbitrary URLs to controllers. Scripts are never "loaded" directly through Apache.

Basically, there are two kinds of routing: static routing and dynamic routing. React routing is one of static routings, which occurs when a router uses a manually-configured routing entry. React Router bootstraps the routes from /node_modules/routes.js file, matches them against a URL, and then executes the appropriate callback handler.

Here is an example how routing works in React:

  import React, { Component } from 'react';
  import { BrowserRouter as Router, Route} from 'react-router-dom';
  const Main = () => (
        <div>
            <Route path="/something" component={SomeComponent} />
            <Route path="/otherthing" component={OtherComponent} />
        </div>);
   ReactDOM.render(<Router><Main /></Router>, document.getElementById('root'));

In server.js (back-end):

 var express = require('express');
 var app = express();
 var path = require('path');
 app.get('/something',(req,res) => {
   	someFunction => {
   		someCallBack;
   	})
   });

What we are doing here is to generates a route entry containing two routes, when the route path is changed to the specific value, it will display the corresponding component and call the corresponding callback function in the back end.