1// Route definition structure
2app.METHOD(PATH, HANDLER)
http
method (GET, POST, PUT, DELETE etc.). You can also use all
as a catchall for any method supported in the http
module (it’ll execute the handler for the URL regardless of the method you are using) app.all(PATH, HANDLER)
1// Routing in Express.js
2// path: ./routes/index.js
3const express = require('express');
4const router = express.Router();
5
6router.get('/', (request, response) => {
7 response.send('Hey it works!');
8})
9
10module.exports = router;
1// path: ./app.js
2const routes = require('./routes/index'); // import our routes
3
4app.use('/', routes); // use the routes file whenever anyone goes to /anything
5app.use('/admin', adminRoutes); // You can have multiple route handlers
1app.all('/secret', (request, response, next) => {
2 response.send('ha!');
3 next() // pass control to the next handler
4});
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()
.json()
.send()
and .json()
), you’re gonna get headers are already sent. So make sure you’re never sending data more than once.next
is for when you don’t want to send any data back or want to pass it along to something else1router.get('/', (req, res) => {
2 let profile = { name: 'Aamnah', age: 100, cool: true };
3 console.log('chal gya!');
4 res.send('chal gya code');
5 res.json(profile);
6})
request.query()
access Query stringsrequest.params()
access URL Parametersrequest.body()
access POSTed valuesFrom the request
you can extract any data that was passed via the URL
For example:
http://localhost:7777/?name=Aamnah&age=100
1router.get('/', (req, res) => {
2 res.send(req.query); // {"name":"\"Aamnah\"","age":"100"}
3 res.send(req.query.name); // Aamnah
4 res.send(req.query.age); // 100
5})
req.query
is an object full of all the query parameters
:
specifies parameters1router.get('/profile/:name', (req, res) => { // :name is a variable
2})
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:
1router.get('/profile/:name/:role', (req, res) => { // http://127.0.0.1:7777/profile/aamnah/admin
2 res.send(`${req.params.name}'s role is ${req.params.role}`); // aamnah's role is admin
3})
Here’s some code to reverse any string sent to a URL endpoint
1router.get('/reverse/:string', (request, response) => { // localhost:port/reverse/aamnah is awesome
2 let reverse = [...request.params.string].reverse().join(''); // using ES6 spread syntax here
3 response.send(reverse); // emosewa si hanmaa
4})