Using Response Methods

Look at how we can use the response methods to redirect requests and set a header.

We'll cover the following...

Redirecting requests

Let’s say we want to redirect requests to different URLs. This will probably be based on an action or the user’s permission level. The following code shows the various methods you can use to do so:

'use strict'

class TestController {
  //Extracting the view class of the HTTP context
  add({ view }) {
    return view.render('add')
  }
  enter({ response }) {
    return response.redirect('/product/add');
  }
  product({ request }) {
    const product_id = request.input('product_id')
    const product_name = request.input('product_name')
    return product_id + ', ' + product_name
  }
  info({ params }) {
    return `Product ID ${params.product_id}`
  }
  macbook({ response }) {
    return response.route('product.info', { product_id: 1 })
    //return response.route('TestController.info', { product_id: 1 })
  }
}

module.exports = TestController

Press Run and wait for the welcome page to be displayed in the Output tab. Then, click on the link under the Run button and append /enter to it. You will be redirected to /product/add ...