1. Initialization
- Project initialization
egg-init spider --type=simple
Copy the code
- Install dependencies
npm i
Copy the code
- Run the test project
npm run dev
Copy the code
- Configuring the Template Engine
npm i egg-view-ejs
Copy the code
- Find the app/config/plugin. Js
exports.ejs = {
enable: true.package: 'egg-view-ejs'
};
Copy the code
- Find the app/config/config. Default. Js
config.view = {
mapping: {
'.html': 'ejs'}}Copy the code
- Configure a public URL address (config/config.default.js)
config.api = "http://www.phonegap100.com/"
Copy the code
Second, grab the news interface to realize the news list and details
- Define the news list and news detail routing
router.get('/news', controller.news.index);
router.get('/newscontent', controller.news.content);
Copy the code
- Get news list data and news detail data in the service
async index() {
let list = await this.service.news.getNewsList();
await this.ctx.render('news',{
list
})
}
async content() {
const aid = this.ctx.query.aid;
console.log(aid);
const detail = await this.service.news.getNewsContent(aid);
await this.ctx.render('newscontent', {detail:detail[0]})}Copy the code
Remember: always use await when rendering, because it is asynchronous rendering, otherwise you may get a 404 error.
- Define the template engine in the View view layer
<h2>News list</h2>
<ul>
<%for (let i = 0; i < list.length; i++) {%>
<li><a href="/newscontent? aid=<%=list[i].aid%>"><%=list[i].title%></a></li>The < %} % ></ul>
Copy the code
Egg.js framework extends extend
Through the Application
- Create a new folder extend under the app folder
- Create an application.js file under the extend folder. Any functions exposed in this file can be called through this.app. XXX, but inside application.js this is app.
module.exports = {
foo(param) {
// This is the app object in which you can call other methods on the app or access properties
console.log(this); }};Copy the code
Through the Context
- Create context.js under extend
- Define the function you want to extend in context.js
module.exports = {
getHost(param) {
// This is the CTX object from which you can call other methods on the CTX or access properties
return this.request.header.host; }};Copy the code
- Call the extended function
console.log(this.ctx.getHost());
Copy the code
For more information on how to expand, visit the website: Egg Expand
Convert the timestamp to a time string in extended form
- Install and introduce relevant modules
const sd = require('silly-datetime')
module.exports = {
formatTime (param) {
// This is a helper object from which other helper methods can be called
// this.ctx => context object
// this.app => Application object
return sd.format(new Date(param*1000),'YYYY-MM-DD HH:mm')}};Copy the code
- Used in a template engine
<%=helper.formatTime(list[i].dateline)%>
Copy the code
- Used in the controller
Through this. CTX. Helper. XXX ()
console.log(this.ctx.helper.sendHello());
Copy the code
By the Request
- Create request.js under extend
module.exports = {
foo() {
return this.header.host
},
};
Copy the code
- Called in the controller
console.log(this.ctx.request.foo());
Copy the code
4. Deny access to the specified IP address
When the Egg calls the middleware
Before or after a route is matched.
Middleware definition and configuration, transmission value
- Create a folder called Middleware under your app folder and create printdate.js underneath
module.exports = (options,app) = > {
console.log(options);
// Return an asynchronous method
return async function printDate(ctx,next) {
console.log(new Date());
awaitnext(); }}Copy the code
- In the config/config. Default. Js
config.middleware = ['printdate'];
config.printdate = {
aaa: '123'
}
Copy the code
Disable access from specified IP addresses
- Create a new forbidip.js in app/ Middleware
module.exports = (options,app) = > {
// Return an asynchronous method
return async function printDate(ctx,next) {
// IP address to mask
const forbidIp = "127.0.0.1";
// Obtain the CLIENT IP address
if (ctx.request.ip === forbidIp) {
ctx.status = 403;
ctx.body = "Your IP has been blocked."
} else {
awaitnext(); }}}Copy the code
- Register the middleware in config/config.default.js
config.middleware = ['printdate'.'forbidip'];
Copy the code
POST to submit data and configure CSRF through middleware
- Define the CSRF in the template engine
<form action="/add? _csrf=<%=csrf%>" method="post"> User name: <input type="text" name="username"><br><br> Password: <input type="password" name="password"><br><br>
<button type="submit">submit</button>
</form>
Copy the code
- Create auth.js under App/Middleware
module.exports = (option,app) = > {
return async function auth(ctx,next) {
// Set the template global variable so that the template engine can fetch CSRF directly instead of passing it every time
ctx.state.csrf = ctx.csrf;
awaitnext(); }}Copy the code
Use cookies in egg.js
- Method to set cookies
this.ctx.cookies.set('name'.'zhangsan');
Copy the code
- Method to get cookies
this.ctx.cookies.get('name');
Copy the code
Now, how do I set cookies in one controller and get cookies in another controller
- The controller that sets the cookie
async index() {
const { ctx } = this;
/ / set the cookie
const username = this.ctx.cookies.set('username'.'zhangsan');
This.ctx. CSRF: generates a key when the user accesses the page
await ctx.render('home')}Copy the code
- The controller that gets cookies
async index() {
const username = this.ctx.cookies.get('username')
await this.ctx.render('news', {
username
})
}
Copy the code
- Example Set the cookie cache validity period
const username = this.ctx.cookies.set('username'.'zhangsan', {maxAge: 1000*3600*24
});
Copy the code
- Set the parameters
const username = this.ctx.cookies.set('username'.'zhangsan', {maxAge: 1000*3600*24.httpOnly: true.signed: true.// Sign cookies to prevent users from modifying cookies
encrypt: true.// If the cookie is encrypted, it needs to be decrypted when it is obtained
});
Copy the code
- Remove the cookie
this.ctx.cookies.set('username'.null)
Copy the code
Seesion is used in egg.js
Cookies are stored on the client’s browser, while sessions are stored on the server. When the browser accesses the server and sends the first request, the server creates a session object, generates a key-value pair similar to key and value, and returns the key(cookie) to the browser. The browser carries the key(cookie) when it accesses the server for the next time. Find the corresponding session(value). When the browser accesses the target server for the first time, the response header of the target server contains a set-cookie field, and the browser accesses the target server for the second time with a cookie.
- Set session in the controller
async setSession() {
this.ctx.session.username = "Aftermath";
}
Copy the code
- Get session from the controller
async index() {
// Get the session and render it to the news page
const username = this.ctx.session.username;
await this.ctx.render('news', {
username
})
}
Copy the code
- Set session expiration time (you can also configure session in config)
this.ctx.session.maxAge = 5000;
Copy the code
- Configure session in config.default.js
config.session = {
maxAge: 1000*5
}
Copy the code