当前位置:网站首页>Nestjs configuration service, configuring cookies and sessions
Nestjs configuration service, configuring cookies and sessions
2022-07-03 11:38:00 【Johnny, me】
About NestJs In the service
- We were Angular Services used in , stay NestJs It also draws on relevant ideas
- stay NestJs The services in can be Service It can also be Provider, All available constructor Injection dependency
- NestJs In the service , amount to MVC Medium Model, Its essence is through @Injectable() Class of decorator annotations
- stay NestJs Medium MVC Medium V(View), launch http After the request , By C(Controller) Receive and return information to V
- stay C The business logic processing in should be concise and simple , stay M Dealing with complex logic
Built in service
When we generate template projects , There is already a service :app.service.ts
@Injectable() export class AppService { getHello(): string { return 'Hello World!'; } }
This service is actually a class , Is a @Injectable Decorator decorated class , stay app.module.ts Introduce and configure
If where to use this service , Where to inject , For example app.controller.ts To call the methods in the service
import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) { } @Get() getHello(): string { return this.appService.getHello(); } }
Create services
- There are two ways to create a service :
- $
nest g service cart
- $
nest g provicer cart
- $
- Commonly used service To create , Create modules in our development , Generally, the controller and service of this module will be created at the same time
- We also use shortcut commands to create , Then write our business logic smoothly
- If we have common business logic , I usually write a general service
- and , If necessary , We can introduce the current service into any controller
- Generally, we are in the controller , First introduce the service , Injection is based on constructor
constructor(private cartService:CartService){}
- When you call it , Directly through this.cartService.xxxx To call
Development template structured configuration
- The structure of the template we created is relatively loose , The controllers and services created later are highly cohesive into separate modules
- In fact, we can also put the controllers together , Services are all put together , But I feel that it can be maintained in this way , Not as good as modularization
- These structures differ from person to person , How to maintain habits , As long as it is convenient to find
Nestjs Medium cookie
1 ) cookie Preliminary use of
Identify user information , Let users share information on multiple pages , At this time, we will base on cookie and session To deal with it
Nestjs By default express Of HTTP When the configuration , We can install express Related plug-ins , such as :cookie-parse
$
yarn add cookie-parser
, stay main.ts Introduce in , And configure middleware// main.ts import * as cookieParser from 'cookie-parser'; // To configure cookie middleware app.use(cookieParser()); // Be careful cookieParser It is best to pass in a key , You can encrypt , Encryption can also be disabled
Test in the controller cookie
import { Get, Response} from '@nestjs/common'; @Controller('user') export class ArticleController { @Get() index(@Response()) res { // Set up cookie The period of validity 1 God , Only the back end can read cookie res.cookie("username", "Joh", { maxAge: 1000 * 60 * 60 * 24, httpOnly: true}) res.send(''); // return ''; // Be careful , Be sure to use send, And not return, Otherwise, it will not respond } // Read cookie @Get('cookie') getCookie(@Request() req) { console.log(req.cookies.username); return 'req.cookies.username'; } }
cookie Common configurations are as follows
domain String domain name expires Date Expiration time (second), After a point in time cookie invalid httpOnly Boolean Through the program (js Script ,applet) Can't read cookie, prevent XSS attack maxAge String Maximum failure time ( millisecond ) Set how many times it will expire secure Boolean If you set true, Only in the https Enter into force path String cookie The path of impact , Default root path / If the set paths do not match , It cannot be carried cookie signed Boolean Whether to sign cookie, Set to true For this cookie Signature , Need to use res.signedCookies Instead of res.cookies visit ; The tampered signature will be rejected by the server ,cookie And will be reset
2 ) cookie Encryption processing of
app.use(cookieParser(‘ Your key ’));
import { Get, Response} from '@nestjs/common'; @Controller('user') export class ArticleController { @Get() index(@Response()) res { // Set up cookie The period of validity 1 God ,httpOnly Only the back end can read cookie,signed encryption cookie res.cookie("username", "Joh", { maxAge: 1000 * 60 * 60 * 24, httpOnly: true, signed: true}) res.send(''); // return ''; // Be careful , Be sure to use send, And not return, Otherwise, it will not respond } // Read cookie @Get('cookie') getCookie(@Request() req) { console.log(req.signedCookies.username); // Get the encrypted cookie, If not , If you write normally, it will be undefined return 'req.cookies.username'; } }
Be careful , Use request Object time , If based on Render Decorator to handle the template engine , You can use return To wrap the data
import { Get, Response, Render} from '@nestjs/common'; @Controller('user') export class ArticleController { @Get() @Render('default/user'); index(@Response()) res { // Set up cookie The period of validity 1 God ,httpOnly Only the back end can read cookie,signed encryption cookie res.cookie("username", "Joh", { maxAge: 1000 * 60 * 60 * 24, httpOnly: true, signed: true}); // Pay attention to the direct return return { name: 'Joh'}; } }
Nestjs Medium session
- session Used to record customer status , and cookie In combination with
- When the client browser first accesses the server , Will create a session object , Generate a similar key,value The key/value pair , And then key(cookie) Back to browser side
- When the browser accesses again , Will carry this key(cookie), Find the corresponding value(session)
- This process is similar to a customer communicating with a bank counter teller with a credit card or ID card
1 ) install express-session
- $
yarn add express-session
2 ) To configure express-session
import * as session from 'express-session';
app.use(session({
secret: 'keyboard cat', cookie: {
maxAge: 1000 * 60 * 60 * 24}}));
3 ) Use session
// Only the key code is written here
index(@Request() req): string {
// Set up session
req.session.username = req.signedCookies.username;
}
4 ) session Common configuration of
app.use(
session(
{
name: 'c.sid', // Return the key The name of , The default is connect.sid, You can also set it yourself
secret: 'keyboard cat', // secret key , One String String of type , As a server-side generation session The signature of the
resave: false, // Force save session Even if it doesn't change ,. The default is true. It is suggested to set it to false
saveUninitialized: true, // Force uninitialized session Storage . When I create a new one session And no property or value is set , It's in an uninitialized state . In setting up a cookie front , This is for login verification , Reduce the storage pressure on the server , Access control helps .( Silent recognize :true).
cookie: {
maxAge: 1000 * 60 * 60 * 24} // cookie To configure , Set back to the front end key Properties of , The default value is { path: ‘/’, httpOnly: true, secure: false, maxAge: null }.
rolling: true, // Force settings on every request cookie, Reset cookie Expiration time ( Default :false)
}
)
);
express-session Common configuration of
// // Set up session
req.session.username='Joh';
// obtain session
req.session.username;
// To reset cookie The expiration time of
req.session.cookie.maxAge=0;
// The destruction session
req.session.destroy(function(err) {
/* ToDo */ })
边栏推荐
- Numpy np.max和np.maximum实现relu函数
- [vtk] source code interpretation of vtkpolydatatoimagestencil
- [OBS] encapsulate the basic process of OBS acquisition
- How to clean up v$rman_ backup_ job_ Details view reports error ora-02030
- STL教程8-map
- C language log base zlog basic use
- PHP Basics
- Hongmeng third training (project training)
- Processes and threads
- Driver development based on I2C protocol
猜你喜欢
多维度监控:智能监控的数据基础
PHP Basics
鸿蒙第三次培训(项目实训)
Cuiyusong, CTO of youzan: the core goal of Jarvis is to make products smarter and more reliable
Application of high-precision indoor positioning technology in safety management of smart factory
How to clean up v$rman_ backup_ job_ Details view reports error ora-02030
GCC compilation process and dynamic link library and static link library
ftp登录时,报错“530 Login incorrect.Login failed”
MATLAB extrait les données numériques d'un fichier txt irrégulier (simple et pratique)
Matlab extracts numerical data from irregular txt files (simple and practical)
随机推荐
CSRF
R language uses grid of gridextra package The array function combines multiple visual images of the lattice package horizontally, and the ncol parameter defines the number of columns of the combined g
多维度监控:智能监控的数据基础
Excel quick cross table copy and paste
uniapp实现点击加载更多
LeetCode 46:全排列
(2) Base
Google Earth engine (GEE) - ghsl global population grid dataset 250 meter resolution
Illustrated network: what is virtual router redundancy protocol VRRP?
After watching the video, AI model learned to play my world: cutting trees, making boxes, making stone picks, everything is good
Technical experts from large factories: how can engineers improve their communication skills?
抓包整理外篇fiddler———— 会话栏与过滤器[二]
Excel快速跨表复制粘贴
Web安全总结
Uniapp implementation Click to load more
R语言使用data.table包进行数据聚合统计计算滑动窗口统计值(Window Statistics)、计算滑动分组中位数(median)并合并生成的统计数据到原数据集中
Using onvif protocol to operate the device
R language uses grid of gridextra package The array function combines multiple visual images of the ggplot2 package horizontally, and the ncol parameter defines the number of columns of the combined g
00后抛弃互联网: 毕业不想进大厂,要去搞最潮Web3
Hongmeng fourth training