0

Creating and Debugging Website Routers

 2 years ago
source link: https://hackernoon.com/creating-and-debugging-website-routers-hh1g34aj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Creating and Debugging Website Routers

5
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png

@veloVelo by Wix

Velo is a full-stack development platform that empowers you to rapidly build, manage and deploy professional web apps.

Creating a router allows you to take complete control when handling certain incoming requests to your site.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

This article takes you through what code you have to write in order to make your router work. To learn more about what a router is and why you would want to create one, see About Routers.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Add a Router

To add a router:

0 reactions
heart.png
light.png
money.png
thumbs-down.png

1. Click on the

0 reactions
heart.png
light.png
money.png
thumbs-down.png

icon that appears when hovering over the Page Code's Main Pages section in the Velo Sidebar and choose Add a Router.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

2. Enter a URL prefix for your router and click Add & Edit Code. All incoming requests with the specified URL prefix will be sent to your router for handling. 

0 reactions
heart.png
light.png
money.png
thumbs-down.png

When adding a router:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
  • Your router's
    router()
    and
    sitemap()
    functions are added in a routers.js file with sample code for a simple routing scenario. The routers.js file is found in the Code Files's Backend section of the Velo Sidebar.
  • A new section, Router Pages, is created in the Velo Sidebar for your routers. Router pages are grouped together under a title based on the prefix you chose earlier. One router page is created to start with. For example, if you named your router "myRouter", a page named myRouter-page is added under the title MyRouter Pages (Router).

Sample Scenario

There are four parts to the sample code that's added to the routers.js file:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
  1. The
    import
    statement.
  2. The sample data.
  3. The
    router()
    function.
  4. The
    sitemap()
    function.

Import statement

0 reactions
heart.png
light.png
money.png
thumbs-down.png

The functionality used to create a router is contained in the Router API. To use this functionality, you need to import it. By default, the

ok()
and
notFound()
functions are imported, as well as the
WixRouterSitemapEntry
object.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
import {ok, notFound, WixRouterSitemapEntry} from "wix-router"; 

If you want to use more of the functionality from the Router API, you need to add it to the

import
statement.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Sample Data

0 reactions
heart.png
light.png
money.png
thumbs-down.png

In the sample scenario, the router uses some static data contained in an object named

peopleData
.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
const peopleData = {  
  "Ash": {    
    title: "Ash Stowe",    
    image: "https://static.wixstatic.com/media/b8f383e0fe2b478ea91362b707ef267b.jpg"  
  },  
  "Aiden": {    
    title: "Aiden Johnson",    
    image: "https://static.wixstatic.com/media/ca3c7ac5427e43928aa5f3f443ae2163.jpg"  
  },  
  "Jess": {    
    title: "Jess White",    
    image: "https://static.wixstatic.com/media/147fe6f37fe24e83977b4124e41b6d3d.jpg"  
  },  
  "Morgan": {    
    title: "Morgan James",    
    image: "https://static.wixstatic.com/media/59e1f2f4dbbc4f7c9d6e66e3e125d830.jpg"  
  }
};

The

peopleData
object contains four keys, each representing a person. Each person contains two properties, a
title
that is the person's full name and an
image
that is a link to an image of the person.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Although you can use static data with a router, typically you would use data
from your site's database or an external source. We'll see where you would write code to retrieve that data a little later.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Regardless of where you get the data from, since you'll be writing the code that handles it, the data can be structured in any way you like.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Router Function

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Remember, all incoming requests with the URL prefix you specified when creating the router are sent to your router for handling. The

router()
function is where you handle those requests.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

The

router()
function is named with the following convention:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
<router prefix>_Router(request)

So if you named your router myRouter, the code added to the routers.js file should look like:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
myRouter_Router(request) {  // routing code ...}

The

router()
function has a request parameter which receives a
WixRouterRequest
object that contains information about the incoming request. The object has information about the URL used to reach the router, where the request came from, and who the request came from.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Typically, the

router()
function will decide which page to show (if any) and what data to pass to the page. A response is then sent using the
forbidden()
,
notFound()
,
ok()
,
redirect()
,
or
sendStatus()
functions.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Let's take a look at the sample

router()
function code:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
export function myRouter_Router(request) {

  // Get item name from URL request
  const name = request.path[0];

  // Get the item data by name
  const data = peopleData[name];

  if (data) {

    //define SEO tags 
    const seoData = { 
      title: data.title, 
      description: `This is a description of ${data.title} page`,
      noIndex: false,
      metaTags: [
         {"og:title": data.title,
          "og:image": data.image,
          content: "People Data"
         }
      ]
    };

    // Render item page 
    return ok("myRouter-page", data, seoData); 
  }

  // Return 404 if item is not found 
  return notFound();
}

The

router()
function begins by parsing the request's path to pull out a name value.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
const name = request.path[0];

For example, a user might reach this

router()
function by browsing to
https://mysite.com/myRouter/Ash
. The received
WixRouterRequest
object's
path
property will be an array with one element:
["Ash"]
. Now the value of name is "
Ash
".
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Next, the

router()
function retrieves data based on the
name
it received.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
const data = peopleData[name];

Continuing our example above, we pull out Ash's information from the

peopleData
object.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

So

data
now holds:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
{ 
  title: "Ash Stowe",
  image: "https://static.wixstatic.com/media/b8f383e0fe2b478ea91362b707ef267b.jpg"
}

If you want to retrieve data from an external source, this is where you place the call to retrieve that data.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

After attempting to retrieve the data that corresponds to the incoming request, we check to see if any data was found:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
if (data) {
  // ...
}

If nothing was found, the

if
is skipped and we return a 404 error using the
notFound()
function.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
return notFound();

Assuming we found the data we were looking for, we now prepare some header data for our page:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
const seoData = { 
  title: data.title, 
  description: `This is a description of ${data.title} page`,
  noIndex: false,
  metaTags: {
    "og:title": data.title,
    "og:image": data.image
  }
};

Here we create a

HeadOptions
object that defines what will be put in the HTML head of the page we respond to the request with. That object is stored in the seoData variable.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

The sample code creates a

title
and
description
based on the
title
property of the retrieved
data
object. It also sets
noIndex
to false, meaning search engines should index the page. Finally, some
metaTags
properties are added as well.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

You can create the

HeadOptions
object using any information you want.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

You can also add a keywords property to the

HeadOptions
object with a string containing the page's keywords.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Finally, we return a

WixRouterResponse
object using the
ok()
function:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
return ok("myRouter-page", data, seoData); 

Here we route the user to the router page named "

myRouter-page
" and pass it the
data
that was retrieved and the
seoData
that was built for the page.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Depending on the situation, you can return a number of different responses from the

router()
function. So far we've seen the
notFound()
and
ok()
functions in use. You can also use the
forbidden()
function to return a
403
response, the
redirect()
function to return a
301
or
302
response, or the
sendStatus()
function to return a response with any status code you choose.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Router Data

0 reactions
heart.png
light.png
money.png
thumbs-down.png

To use the data that was returned with a

WixRouterResponse
using the
ok()
function, use the
wix-
window
getRouterData()
function.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

For example, we can take the data passed by the sample router code and use it to present a person's information on the myRouter-page page that was created.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

First, we need to add a text and image element to serve as placeholders for a person's title and image.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Next, in the page's code we retrieve the router data and set the text and image elements to display the

title
and
image
from the data.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
import wixWindow from 'wix-window';

$w.onReady(function () {
  let data = wixWindow.getRouterData();
  $w("#text1").text = data.title;
  $w("#image1").src = data.image;
});

If you preview the page, you'll see that the placeholders we put on the page are filled in with information from the data that was passed to the page. You can use the preview widget to see what the page looks like for any of the people in the

peopleData
object that was defined in the routers.js file.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

The preview widget gets populated with the

title
values from the
WixRouterSitemapEntry
objects that are returned by the router's
sitemap()
function.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Sitemap Function

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Like the

router()
function, the
sitemap()
function is named with the following convention:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
<router prefix>_Sitemap(sitemapRequest)

So if you named your router myRouter, the code added to the routers.js file should look like:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
myRouter_Sitemap(sitemapRequest) {  // routing code ...}

The

sitemap()
function has a
sitemapRequest
parameter which receives a
WixRouterSitemapEntry
object that contains information about the incoming request. The object has information about the URL used to reach the router, the pages in the router, and who the request came from.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Typically, the

sitemap()
function creates a
WixRouterSitemapEntry
object for each item in the data used by the router. So, in our example, we create an entry for each person in the
personData
object. You also might want to include entries for other pages, like an index page or a search page.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Let's take a look at the sample

sitemap()
function code:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
export function myRouter_SiteMap(sitemapRequest) {

  // Convert the data to site map entries
  const siteMapEntries = Object.keys(peopleData).map( (name) => {
    const data = peopleData[name];
    const entry = new WixRouterSitemapEntry(name);
    entry.pageName = "myRouter-page"; // The name of the page in the Wix Editor to render
    entry.url = `/myRouter/${name}`; // Relative URL of the page
    entry.title = data.title;   // For better SEO - Help Google
    return entry;
  } );

  // Return the site map entries
  return siteMapEntries;
}

The

sitemap()
function takes the keys of the peopleData object and uses the JavaScript
map()
function to create an array of
WixRouterSitemapEntry
objects, one object for each key. Each entry is given values for the
pageName
,
url
, and
title
properties. Then the array is wrapped in a
Promise
and returned.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

A sitemap entry can also contain

changeFrequecy
,
lastModified
, and
priority
properties to give search engines more information about each page.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

In a case where you're using a router with external data, in the

sitemap()
function you would retrieve that data and build sitemap entries for each item that was retrieved.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Previously published at https://support.wix.com/en/article/velo-creating-a-router

0 reactions
heart.png
light.png
money.png
thumbs-down.png
5
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png
by Velo by Wix @velo. Velo is a full-stack development platform that empowers you to rapidly build, manage and deploy professional web apps.Develop Smarter, Deliver Faster
Join Hacker Noon

Create your free account to unlock your custom reading experience.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK