Continue to Express.js
date 23.02.2021
With Express.js we can use requests and responses. Request is coming to Express and response is going from Express.
Sending a Response
With Express we can easly send responses. With this code we're sending string as a response: ```asm res.send('Hi') ```asm
If we want to send json response: ```asm res.json({ message: 'Hi', name: 'Berkay' }) ```asm
Response Types
We can change response types as well: ```asm res.type('html') // text/html
res.type('json') // application/json
res.type('png') // image/png ```asm
Response Headers
Changing headers are easy: ```asm res.set('Authorization', 'token')
res.set('Content-Type', 'application/json') ```asm
Response Cookies
Sometimes we'll want to add cookies to our responses: ```asm res.cookie('token', 'supersecrettoken') ```asm
You can also delete cookies ```asm res.clearCookie('token') ```asm
Response Status
We can set our response status: ```asm res.status(404).json({ message: 'Not found' }) ```asm
You can do the samething with a shortcut: ```asm res.sendStatus(404) // => res.status(404).send('Not found') ```asm
Response Redirect
With a simple response you can redirect your users: ```asm res.redirect('https://berkaycubuk.com')
res.redirect('./')
res.redirect('back') // sending users back ```asm
Routing
Routes are simply directions where we are accepting requests. For example: ```asm app.get('/login', (req, res) => {}) ```asm
In this example, we opened our gates for the "/login" address, but only for get request.
Routes With Parameters
We want to create a blog and we have "/post" route. Our visitors will be normal people so they are not using any API tools, they will use their browser to access our website. What if they only want to see a single post? We have to get some data with the url, to do that: ```asm app.get('/post/:postName', (req, res) => { res.send(req.params.postName) }) ```asm
This example sends user back the parameter.
Middleware
Middlewares are a function that we can connect to routes. We can run it in all requests or we can run it on specific requests. They all can work together, that means you can use multiple middlewares. Let's understand it with an example: ```asm const express = require('express') const app = express()
app.use(express.json()) ```asm
In this example we used Express's built in json function. It helps us to use json in our responses and requests. It runs in every request. Time to create our own and adding it to specific routes. ```asm const myMiddleFunc = (req, res, next) => { // do what you want in here next() // sending the ball to the next one }
app.get('/', myMiddleFunc, (req, res) => {}) ```asm
With this, we created simple function that does what you want and when it's finish it's job, going to next middleware. To add middlewares to specific routes, we can pass them to route as a parameter.