关于eggjs:eggjs-连接远程-mysql-数据库

作为一个正在学习后端常识的菜鸟,最后存储数据的形式是通过 fs 模块存到本地的 JSON 文件中的。起初感觉太 low 还是得用上 mysql。 服务器 mysql 装置我是在腾讯云的宝塔面板界面化装置的,本地装置能够去这里下载并装置。装置实现后,试了一些命令确定装置胜利。 # 查看 mysql 的状态$ systemctl status mysqld# 启动 mysql$ systemctl start mysqld# 应用 root 权限登录 mysql$ mysql -u root -p题外话,忽然想起来无论是 nginx 还是 mysql 的启动和查看状态都是用的 systemctl 命令。 $ systemctl start nginx$ systemctl status nginxmysql 连贯我的 node 我的项目用到的是 egg.js。文档十分敌对,很粗疏的阐明了如何连贯数据库,详见MySQL - Egg。 装置依赖库$ npm i --save egg-mysql开启插件// config/plugin.jsexports.mysql = { enable: true, package: 'egg-mysql',};配置数据库信息// config/config.${env}.jsexports.mysql = { // 单数据库信息配置 client: { // host host: 'mysql.com', // 端口号 port: '3306', // 用户名 user: 'test_user', // 明码 password: 'test_password', // 数据库名 database: 'test', }, // 是否加载到 app 上,默认开启 app: true, // 是否加载到 agent 上,默认敞开 agent: false,};遇到的问题无法访问近程服务器发现是我的腾讯云服务器的 3306 端口未凋谢,关上之后就好了。 ...

February 27, 2023 · 1 min · jiezi

关于eggjs:初始Egg框架

前言作为一名前端从业者不会点后端的常识怎么能够。node.js成为了前端理解后端的首选。工欲善其事,必先利其器本。一款好的框架。是提效的基本。这是一篇从0到1入门egg的文章。 三者区别与分割Express是基于 Node.js平台,疾速、凋谢、极简的 Web 开发框架,老牌框架,很多风行的框架的基石,简略且扩展性强,适宜做集体我的项目,本身短少束缚。Koa是基于Node.js平台的下一代web框架,由Express原班人马打造。特点:玲珑灵便简略易用。作为企业级开发过于根底。Egg为企业级框架和利用而生,奉行约定优于配置。Egg 继承于 Koa特点: 提供基于 Egg [定制下层框架]的能力高度可扩大的[插件机制]内置[多过程治理]基于 [Koa]开发,性能优异框架稳固,测试覆盖率高[渐进式开发] 起步初始化我的项目:(脚手架) $ mkdir project-name//创立一个空的文件夹$ npm init egg --type=simple//simple示意骨架类型 $ npm install || i //装置依赖初始化我的项目后构造目录如图所示启动我的项目 $ npm run dev//开发环境中应用$ npm run start//生产环境中应用文件目录介绍次要文件目录介绍 |-app//次要开发的文件| |-- controller//解析用户的输出,解决后返回相应的后果| |-- db//启动mongodb数据库的dbpath门路(可选)| |--extend//框架的扩大(内置对象扩大)| | |---application.js//(固定名称)| | |---context.js//(固定名称)| | |---request.js//(固定名称)| | |---response.js//(固定名称)| | |---helper.js//(固定名称)| |--middleware//编写中间件| |--model//数据库中表的模型| |--publie//动态资源| |--schedule//定时工作| |--service//编写业务逻辑层| |--view//模板文件| |---router.js//配置 URL 路由|-config//寄存配置文件| |--config.default.js//用于编写配置文件| |--plugin.js//配置须要加载的插件|-test//寄存单元测试|-logs//日志文件|-package.json//我的项目形容内置对象Application//全局利用对象=》继承于koaContext//申请级别对象=》继承于koaRequest//申请级别对象=》继承于koaResponse//申请级别对象=》继承于koaController//基类Service//基类Helper//提供一些实用的 utility 函数,本身是一个类Config//配置Logger//功能强大的日志性能Subscription//基类定时工作 路由(router)路由的作用:用来形容申请 URL 和具体承当执行动作的 Controller 的对应关系,用于对立所有路由规定。根本应用办法:在app/router.js中定义url的规定 'use strict';module.exports = app => { const { router, controller } = app; //注册接口 router.get('/logon', controller.logon.Logon);/***路由参数阐明*1.get申请*2.url为/logon*3.执行controller文件夹下的logon文件中的Logon办法**/ };路由实战1.参数获取如果是get申请 ...

March 1, 2022 · 2 min · jiezi

关于eggjs:解决eggmysql插件连接不上mysql问题

解决egg-mysql连贯不上MySql服务器报错:Client does not support authentication protocol requested by server; consider upgrading MySQL client 问题起因通过相干问题查阅,发现是因为navicat版本的问题造成连贯失败。mysql8 之前的版本中加密规定是mysql_native_password,而在mysql8之后,加密规定是caching_sha2_password MySql查看版本号-1 LITING:~ liting$ mysql -uroot -p // 进入mysqlEnter password: //输出mysql明码,如下提醒示意登录胜利Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 24Server version: 8.0.14 MySQL Community Server - GPLCopyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> MySql查看版本号-2(能够进入mysql后通过mysql命令查看) ...

February 23, 2022 · 2 min · jiezi

关于eggjs:Eggjs使用redis实现跨域缓存Fetch发送跨域请求

前后端拆散开发时,咱们的前端申请是跨域申请,会造成session和cookie生效的问题。在浏览多种解决办法后,我抉择了应用redis来实现session的解决方案,确保前端应用跨域申请的状况下,后端能够维持用户session. 起因为什么抉择redis来实现跨域下的session呢?我浏览了多种跨域session失落的解决办法,但都没有失效,于是最初抉择了redis才解决了这个问题。 前后端增加credential后,浏览器无奈主动加载第三方cookie, 服务端的session和cookie依然失落。 前端Fetch跨域申请const data = {key:"value"};// 参数const myHeaders = new Headers();myHeaders.append('Access-Control-Allow-Origin', 'http://localhost:3000/'); // 设置Access-Control-Allow-Credentials,跨域申请带受权myHeaders.append('Access-Control-Allow-Credentials', 'true'); // 设置mode为cors,进行跨域申请myHeaders.append('mode', 'cors'); // 设置Content-Type, 参数格局myHeaders.append('Content-Type', 'application/x-www-form-urlencoded')var urlencoded = new URLSearchParams()for (let key in data) { urlencoded.append(key, data[key])}const requestOptions = { method: 'POST', headers: myHeaders, body: urlencoded, redirect: 'follow', // 设置为include确保跨域申请放弃cookie credentials: 'include', }fetch(api, requestOptions).then(response=>response.json());Egg跨域配置// config.default.js'use strict'const path = require('path')module.exports = appInfo => { const config = { mode: 'file', errorHandler: { match: '/' }, } // 设置security里的csrf敞开,容许跨域申请 config.security = { domainWhiteList: ['*'], csrf: { enable: false } } // 设置cors插件配置, origin为前端的起源(带credentials无奈设置为*) // 设置credentials为true,返回的Header带有Access-Control-Allow-Credentials为true config.cors = { origin: 'http://localhost:3000', credentials: true, allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH' } // 这里设置egg自带的session,但跨域申请依然失落session config.session = { key: 'WheelFit', maxAge: 30 * 24 * 3600 * 1000, // 30 days httpOnly: true, encrypt: true, renew: true } // 自定义中间件, sessionToken为鉴权中间件,在收到申请后获取session里存储的token config.middleware = ['sessionToken', 'errorHandler'] return { ...config, }}// plugin.js'use strict';// 增加cors插件用于回复跨域申请// npm i --save egg-corsmodule.exports = { cors: { enable: true, package: 'egg-cors', }};这个配置是在其余的解决跨域session失落问题的文章中找到的,实践上增加credientals即可放弃session,但我这里并没有失效,跨域申请依然会失落session,并且给response设置的cookie也不能被浏览器获取到。然而应用postman,发送非跨域申请,是能够记录的session的。 ...

November 23, 2021 · 2 min · jiezi

关于eggjs:eggjs-框架安全

/** * security options * @member Config#security * @property {String} defaultMiddleware - default open security middleware * @property {Object} csrf - whether defend csrf attack * @property {Object} xframe - whether enable X-Frame-Options response header, default SAMEORIGIN * @property {Object} hsts - whether enable Strict-Transport-Security response header, default is one year * @property {Object} methodnoallow - whether enable Http Method filter * @property {Object} noopen - whether enable IE automaticlly download open * @property {Object} nosniff - whether enable IE8 automaticlly dedect mime * @property {Object} xssProtection - whether enable IE8 XSS Filter, default is open * @property {Object} csp - content security policy config * @property {Object} referrerPolicy - referrer policy config * @property {Object} dta - auto avoid directory traversal attack * @property {Array} domainWhiteList - domain white list * @property {Array} protocolWhiteList - protocal white list */ exports.security = { domainWhiteList: [], protocolWhiteList: [], defaultMiddleware: 'csrf,hsts,methodnoallow,noopen,nosniff,csp,xssProtection,xframe,dta', csrf: { enable: true, // can be ctoken or referer or all type: 'ctoken', ignoreJSON: false, // These config works when using ctoken type useSession: false, // can be function(ctx) or String cookieDomain: undefined, cookieName: 'csrfToken', sessionName: 'csrfToken', headerName: 'x-csrf-token', bodyName: '_csrf', queryName: '_csrf', // These config works when using referer type refererWhiteList: [ // 'eggjs.org' ], }, xframe: { enable: true, // 'SAMEORIGIN', 'DENY' or 'ALLOW-FROM http://example.jp' value: 'SAMEORIGIN', }, hsts: { enable: false, maxAge: 365 * 24 * 3600, includeSubdomains: false, }, dta: { enable: true, }, methodnoallow: { enable: true, }, noopen: { enable: true, }, nosniff: { enable: true, }, referrerPolicy: { enable: false, value: 'no-referrer-when-downgrade', }, xssProtection: { enable: true, value: '1; mode=block', }, csp: { enable: false, policy: {}, }, ssrf: { ipBlackList: null, checkAddress: null, }, };版权申明:本文为CSDN博主「beginnboyer」的原创文章,遵循CC 4.0 BY-SA版权协定,转载请附上原文出处链接及本申明。原文链接:https://blog.csdn.net/wenrenn... ...

July 2, 2021 · 2 min · jiezi

关于eggjs:eggmonoose-Cannot-read-property-Schema-of-undefined

问题这周有个需要是应用 egg.js 接入 MongoDB 数据库,于是先依照官网举荐的形式应用 egg-mongoose,然而在依照文档进行操作写 demo 时呈现了十分诡异的谬误TypeError: Cannot read property 'Schema' of undefined,app.mongoose app 下的 mongoose 没有被失常挂载上。 // config/plugin.jsmodule.exports = { ... 省略其余不相干配置 mongoose: { enable: true, package: 'egg-mongoose', },};// config/config.default.jsmodule.exports = appInfo => { /** * built-in config * @type {Egg.EggAppConfig} **/ const config = exports = {}; ... 省略其余不相干配置 config.mongoose = { client: { url: 'mongodb://xxxx:30000', options: { mongos: true, dbName: 'xxx', user: 'xxx', pass: 'xxx', }, }, }; return { ...config, };}// {app_root}/app/model/user.jsmodule.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const UserSchema = new Schema({ userName: { type: String }, password: { type: String }, }); return mongoose.model('User', UserSchema);}排查思路首先确认有没有拼写错误,没有的话间接用最小化形式应用 egg-mongoose 是否能够复现来确认是不是文档呈现了问题。测试后发现失常。接下来就是排查本地代码,发现是因为 egg-sequelize 导致的,而局部业务接口之前配置了应用 MySQL 数据库。 egg-sequelize 和 egg-mongoose 默认都是加载 app/model 下的文件,具体逻辑后续详说。 ...

January 2, 2021 · 1 min · jiezi

关于eggjs:如何用Eggjs从零开始开发一个项目2

在上一篇文章,咱们曾经应用Sequelize连贯上了数据库,并能进行简略的数据库操作,在此基础上,咱们试着来开发一个残缺的我的项目。这篇文章咱们从用户的注册、登录着手,试着开发用户模块的相干的代码。 用户注册1. 注册逻辑用户注册的逻辑很简略: 客户端:用户输出输出账号,明码等信息进行用户注册;服务端:接管到客户端提交的注册信息后,进行字段的测验(是否必填、字段长度等),字段符合要求后,依据用户注册的账号查询数据库,依据返回后果判断该用户是否是新用户,如果是新用户,将用户信息写入到数据库,实现注册流程。2. 用户明码解决客户端用户提交数据后,服务端验证通过进行数据库写入,然而其中用户明码是敏感信息,为了服务平安思考,不能间接将明文明码写入到数据库,避免数据库被攻打,用户明码泄露。所以个别在存储用户明码时,会先对用户明码进行加盐加密解决,这样哪怕数据库存储的明码泄露,其他人也无奈通过解决后的明码进行登录。这里应用哈希算法对明码进行加密,因为哈希的个性是不可逆,具体的细节能够参考为什么说 MD5 是不可逆的?。阐明:哈希能够被暴力破解,加盐能够很大水平上减少破解难度。 废话不多说,咱们上面来写代码。 首先,咱们装置一下bcryptjs,咱们应用它对明码进行加盐加密和比对: npm install bcryptjs --save而后咱们把这两个办法写到app/extend/helper.js: const bcrypt = require('bcryptjs');module.exports = { encrypt(password) { const salt = bcrypt.genSaltSync(5); //加盐 const hash = bcrypt.hashSync(password, salt); //哈希(同步调用) return hash; }, compare(password, hash) { return bcrypt.compareSync(password, hash); //比对 }};这样咱们在我的项目里就能够通过this.ctx.helop.encrypt和this.ctx.helop.compare的形式去应用这些专用的办法了。 而后,在UserController中增加一个register办法: async register() { const params = this.ctx.request.body; // 参数校验 if (!params.name || !params.password || !params.phone || !params.email) { this.ctx.body = { code: '500', msg: '参数不非法' }; } // 查问该用户是否曾经注册 const user = await this.ctx.model.User.findOne({ where: { name: params.name } }); if (user) { this.ctx.body = { code: '500', msg: '该用户已存在' }; } // 插入数据库 const result = await this.ctx.model.User.create({ ...params, password: this.ctx.helper.encrypt(params.password) }); if (result) { this.ctx.body = { code: '200', msg: '注册胜利' }; }}最初,增加路由: ...

December 23, 2020 · 2 min · jiezi

关于eggjs:实战搭建完整的IM即时通讯应用2

即时通讯应用服务,整套蕴含服务端、治理端和客户端,欢送Star反对和查看源码。 现已部署上线,欢送体验客户端和治理端 咱们书接上文,持续实现残缺的即时通讯服务,这篇着重讲下Server端我的项目中我认为几个重要的点,大部分内容须要去我的仓库源码和 egg 官网查看。 server 端具体阐明应用脚手架npm init egg --type=simple初始化 server 我的项目,装置 mysql(我的是 8.0 版本),配置上 sequelize 所需的数据库链接明码等,就能够启动了着重讲下 Server 端我的项目中我认为几个重要的点,大部分内容须要去 egg 官网查看。 // 目录构造阐明├── package.json // 我的项目信息├── app.js // 启动文件,其中有一些钩子函数├── app| ├── router.js // 路由│ ├── controller│ ├── service│ ├── middleware // 中间件│ ├── model // 实体模型│ └── io // socket.io 相干│ ├── controller│ └── middleware // io独有的中间件├── config // 配置文件| ├── plugin.js // 插件配置文件| └── config.default.js // 默认的配置文件├── logs // server运行期间产生的log文件└── public // 动态文件和上传文件目录路由Router 次要用来形容申请 URL 和具体承当执行动作的 Controller 的对应关系,即 app/router ...

July 20, 2020 · 4 min · jiezi