1、配置淘宝镜像
(1)通过命令配置
npm config set registry https://registry.npm.taobao.org
npm config get registry
返回https://registry.npm.taobao.org,说明镜像配置成功
(2)通过使用cnpm安装
npm install -g cnpm --registry=https://registry.npm.taobao.org
2、项目配置
(1)安装脚手架
npm init egg --type=simple
(2)配置服务器基本信息
//config.default.js文件
//更改端口号
config.cluster = {
listen: {
path: '',
port: 81,
hostname: '' //默认localhost和ip地址,上线时用0.0.0.
}
};
(3)前端post传参
post请求参数时,会有安全验证问题,简单的处理方式是关闭安全验证,即在config中的config.default.js文件中添加如下代码:
//config.default.js文件
//post发送数据需要关闭csrf(即打开该代码)
config.security = {
csrf: {
enable: false
}
};
(4)获取上传的文件
//config.default.js文件
//开启file模式,可以上传文件
config.multipart = {
mode: 'file',
};
存储图片到本地,地址保存在数据库:
const fs = require('fs'); //导入fs模块
//存储用户信息到数据库
async register(params, files) {
let oldpath = files[0].filepath;
let newpath = __dirname + "/../public/upload/" + files[0].filename;
fs.rename(oldpath, newpath, () => { });
params.headpic = "http://localhost:81/public/upload/" + files[0].filename;
const sql = `insert into user(username,email,pwd,headpic) values("${params.username}","${params.email}","${params.pwd}","${params.headpic}")`;
this.app.mysql.query(sql);
}
(5)MySql数据库操作
egg.js框架提供了egg-mysql插件来访问 MySQL 数据库
npm i --save egg-mysql
//config.default.js文件
//配置数据库
config.mysql = {
client: {
//host
host: "localhost",
//端口
port: "3306",
//用户名
user: "root",
//密码
password: "root",
//数据库名
database: "vue"
}
};
//plugin.js文件
//开启访问数据库插件
mysql: {
enable: true,
package: "egg-mysql"
},
(6)egg跨域
egg.js框架提供了 egg-cors 插件来实现cors跨域请求
npm i --save egg-cors
//config.default.js文件
//跨域的配置
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};
//plugin.js文件
//跨域处理
cors: {
enable: true,
package: 'egg-cors',
}
(7)验证码模块
cnpm i svg-captcha --save
(8)session缓存配置
//config.default.js文件
//session缓存的配置
config.session = {
key: 'EGG_SESS',
maxAge: 24 * 3600 * 1000, // 1 天
httpOnly: true,
encrypt: true,
};
(9)npm run dev启动服务器
3、完整的配置
运行指令
npm init egg --type=simple
npm i --save egg-mysql
npm i --save egg-cors
npm i svg-captcha --save
config.default.js文件
// 更改端口号
config.cluster = {
listen: {
path: '',
port: 81,
hostname: ''
}
};
//post发送数据需要关闭csrf(即打开该代码)
config.security = {
csrf: {
enable: false
}
};
//开启file模式,可以上传文件
config.multipart = {
mode: 'file',
};
// 配置数据库
config.mysql = {
client: {
//host
host: "localhost",
//端口
port: "3306",
//用户名
user: "root",
//密码
password: "root",
//数据库名
database: "vue"
}
};
//跨域的配置
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};
//session缓存的配置
config.session = {
key: 'EGG_SESS',
maxAge: 24 * 3600 * 1000, // 1 天
httpOnly: true,
encrypt: true,
};
plugin.js文件
//开启访问数据库插件
mysql: {
enable: true,
package: "egg-mysql"
},
//跨域处理
cors: {
enable: true,
package: 'egg-cors',
}