Documentation Tutorials

Routing

Routing functions

import {
  htmlRoute,
  route,
  postRoute,
  notFound
} from 'js-web'

route

route(uri,function)

The route function is responding to a GET request, matching the uri parameter.

The function passed to the route can return an object or a redirect. If you pass an object, the route function will send the object as a json result.

route('/user-list', async (input,session,cookie) => {
 return {users: arrayOfUsers}
})

postRoute

postRoute(uri,function)

The postRoute function is similar to the route except it is responding to a POST request.

postRoute('/user-list', async (input,session,cookie) => {
 return {users: arrayOfUsers}
})

htmlRoute

htmlRoute(uri,pathToHtmlFile,function,injections)

The htmlRoute function is responding to a GET request.

The function passed through the route can return an object. This object will be used as context in the passed html file. Read more on Templating.

You can read about the injections parameter here Injections

const injections = [
  inject.style('style/main.css'),
  inject.script('script/script.js')
]

htmlRoute('/','html/index.html',(input, session) => {
  return { hello: 'World' }
}, injections)
htmlRoute('/','html/index.html',(input, session) => {
return { hello: 'World' }
})

Parameters

You can accept parameters in all the route functions.

post('/user/:id', async (input,session,cookie) => {
 // input.id
})

Redirect

You can return a redirect in all routes.

post('/user/:id', async (input,session,cookie) {
 return redirect('/home')
})
post('/user/:id', async (input,session,cookie) {
 return back()
})

Route callback function

The callback function will receive three parameters: input, session and cookie

Input

The input variable contains all inputs sent to the route.

  • route parameters (/user/:id)
  • posted inputs
  • url query parameter

It has an only function, so you can filter inputs.

(input,session,cookie) => {
 user.create( input.only(['name','email']) )
}

Session

The session variable contains four functions: get,set,getFlash and setFlash.

(input,session,cookie) => {
 session.get('key','defaultValue')
 session.getFlash('key','defaultValue')
 session.set('key','value')
 session.setFlash('key','value')
}

Cookie

The cookie variable contains two functions: get and set.

(input,session,cookie) => {
 cookie.get('key','defaultValue')
 cookie.set('key','value')
}

404 / Not found

Display html.

notFound('html/not-found.html', null ,injections)

Redirect.

notFound(null, _ => redirect('/'))