Routing
September 1, 2017
- Routing is all about handling routes, .i.e URL paths. What to do/present/show when someone goes to a route (aka a URL or a path)
- routes are URL handling code
code
// Route definition structure
app.METHOD(PATH, HANDLER);
- The METHOD could be any
httpmethod (GET, POST, PUT, DELETE etc.). You can also useallas a catchall for any method supported in thehttpmodule (it'll execute the handler for the URL regardless of the method you are using)app.all(PATH, HANDLER) - The HANDLER could be a callback function, or a file (module) that has the router defined (containing all the routes)
code
// Routing in Express.js
// path: ./routes/index.js
const express = require("express");
const router = express.Router();
router.get("/", (request, response) => {
response.send("Hey it works!");
});
module.exports = router;
code
// path: ./app.js
const routes = require("./routes/index"); // import our routes
app.use("/", routes); // use the routes file whenever anyone goes to /anything
app.use("/admin", adminRoutes); // You can have multiple route handlers
Callback / Handlers
code
app.all("/secret", (request, response, next) => {
response.send("ha!");
next(); // pass control to the next handler
});
In the response (it doesn't have to be called response, it's just a variable name you'll use inside the function, you can call it dodo for all that matters, but you'll most commonly see it defined as res), you can:
console.log()things- send back text
.send() - send back JSON data
.json() - if you send data twice (e.g. using both
.send()and.json()), you're gonna get headers are already sent. So make sure you're never sending data more than once. nextis for when you don't want to send any data back or want to pass it along to something else
code
router.get("/", (req, res) => {
let profile = { name: "tasiomind", age: 100, cool: true };
console.log("chal gya!");
res.send("chal gya code");
res.json(profile);
});
request.query()access Query stringsrequest.params()access URL Parametersrequest.body()access POSTed values
Query strings
From the request you can extract any data that was passed via the URL
For example:
code
http://localhost:7777/?name=tasiomind&age=100
code
router.get("/", (req, res) => {
res.send(req.query); // {"name":"\"tasiomind\"","age":"100"}
res.send(req.query.name); // tasiomind
res.send(req.query.age); // 100
});
req.query is an object full of all the query parameters
Parameters
:specifies parameters
code
router.get("/profile/:name", (req, res) => {
// :name is a variable
});
Now it'll handle URLs in the structure of /profile/whomever, where whomever is the value of the name parameter. You can access these parameters values like so:
code
router.get("/profile/:name/:role", (req, res) => {
// http://127.0.0.1:7777/profile/tasiomind/admin
res.send(`${req.params.name}'s role is ${req.params.role}`); // tasiomind's role is admin
});
Here's some code to reverse any string sent to a URL endpoint
code
router.get("/reverse/:string", (request, response) => {
// localhost:port/reverse/tasiomind is awesome
let reverse = [...request.params.string].reverse().join(""); // using ES6 spread syntax here
response.send(reverse); // emosewa si hanmaa
});