I can't make work a simple JavaScript app using page.js for the routing functionality

61 views Asked by At

I am trying to learn how a small routing library for javascript apps works - page.js So I made one very tiny app for my own learning purposes but for some reason i can't make it work properly. The app is really as simple as it gets - one folder named test-routing with one file and one folder in it - index.html and src; the src folder has also one file - app.js and another folder- views, with 3 files in it - home.js, page1.js and page2.js

The html file has empty body tag and in the head tag I wrote this: <script src="./src/app.js" type="module"></script>

In the app.js there is this:

import page from '../node_modules/page/page.mjs';

import { home } from './views/home.js';

import { page1 } from './views/page1.js';

import { page2 } from './views/page2.js';

page('/',home);

page('/first',page1);

page('/second/:id',page2);

page.start();

Each of the three files in the views folder has one line of code:

home.js
export function home(){ console.log('HOME PAGE'); }

page1.js
export function page1(){ console.log('PAGE ONE'); }

page2.js
export function page2(context, next){ console.log('PAGE TWO', context.params.id); }

Together with page.js I also installed locally live-server. I ran it and it started working properly on port 8080.

My expectations were that when I go to http://localhost:8080 I would find 'HOME PAGE' in the console and that was indeed the case.

But when I tried with http://localhost:8080/first and http://localhost:8080/second/2, I received in both cases 404 (Not Found) in the console instead of 'PAGE ONE' and 'PAGE TWO 2' and it was also printed in the web page itself 'Cannot GET /first' and 'Cannot GET /second/2' respectively.

Can anyone tell me where I went wrong, please?

Thank you very much in advance!

1

There are 1 answers

0
terola53 On

Either use lite-server (install with npm) or go to live-server's settings, find file setting and set it to "/" If that helps the setting description is : "When set, serve this file (server root relative) for every 404 (useful for single-page applications)"