sails其实是内置的express,所以如果你之前使用的是express,那么你将很快的入门该框架,因为sails基本的语法同express相同,只不过sails集成了很多其他工具,使得我们开发更简单。

今天我只是记录一下它的使用方法,方便日后查看。

1、全局安装:

cnpm install -g sails

2、创建项目:

sails new sails_shop

,选2
    或者:

sails new sails_shop --fast

,选2

cd sails_cqwu
cnpm install //注:安装依赖包

3、启动项目:

sails lift

4、使用自动路由:

修改config->blueprints.js->actions: true

5、创建路由控制:

sails generate controller users zhuce login logout//这个users有login、logout等功能

6、自定义路由:

config->routes.js
 '方式 请求名':{响应方式:'路由'} 注:方式省略表示ALL,action方式可简写为字符串'/': { view: 'index' },'GET /users': {action: 'users/logout'},也可:'GET /users': 'users/logout','/users/login': { action: 'users/login' },'POST /users/zhuce': { view: 'users/zhuce' }

7、对主页模板进行渲染:config->routes.js

'/': function (req,res) {req.session.logined="bbbbb";res.view('index',{title:req.session.logined})},

8、主页渲染方式2
  在config->routes.js中修改根路由:
  形如:  '/': 'UsersController.index',
  在UsersController.js中添加主页路由:
  形如:

  index: async function (req, res) {res.view('index',{title:99});},

9、前台访问:http://localhost:1337
10、修改端口:config->local.js

   module.exports = {port:1338}

11、不使用默认布局:config->views.js
    layout: false
    某个模板不使用布局文件:
    res.view({layout:false});
12、使用自定义的布局文件:在路由或控制器的渲染中添加属性layout

 req.session.logined="bbbbb";res.view('index',{layout: 'layouts/manage',title:req.session.logined})

13、连接数据库(这里我连接的是mongodb)

  cnpm install sails-mysql --save --save-exactcnpm install sails-mongo --save //--save 把安装的模块写进package.json<!--config/datastores.js-->module.exports.datastores = {default: {adapter: 'sails-mysql',url: 'mysql://user:password@localhost:3306/my_db_name',},mongoDb: {adapter: 'sails-mongo',url: 'mongodb://root:@localhost:27017/shop'}};<!--config/models.js-->schema: true,//严格匹配数据表的模式migrate: 'alter',//允许sails修改表的结构attributes: {createdAt: { type: 'number', autoCreatedAt: true, },updatedAt: { type: 'number', autoUpdatedAt: true, },id: { type: 'number', autoIncrement: true, }//id: { type: 'string', columnName: '_id' } 注:mongodb使用}//允许sails自动添加三个字段

14、创建model(根下)

sails generate model admin//创建表或集合

15、修改model文件
  打开Admin.js,添加形如下表属性或结构:
    attributes: {
      zh: {type: 'string', required: true},
      nc: {type: 'string', required: true},
      pwd: {type: 'string', required: true}
    }

  //详细设置参见:数据库表各字段属性设置.html
16、应用model,典型应用在控制器或数据操作模块下:
  添加:
    let rows=await Admin.create({zh: 'lcjtmp6@163.com1', nc: '六六六1', pwd: '6661'}).fetch();
    await//解决异步问题
    .fetch()//返回你刚插入的记录
    console.log(rows);
    return res.send('ok');
    自动接收数据并插入表中方式:
    let reg_info=req.allParams();
    console.log(reg_info);
    let row=await Manage.create(reg_info).fetch();

添加多条数据:
      let data=[
        {zh: 'lcjtmp1@163.com1', nc: 'aaaa1', pwd: '6661'},
        {zh: 'lcjtmp2@163.com1', nc: 'bbbb1', pwd: '6661'},
        {zh: 'lcjtmp3@163.com1', nc: 'cccc1', pwd: '6661'}
      ];
      let rows=await Admin1.createEach(data).fetch();
      console.log(rows);
      return res.send('ok');

查询:
    let rs = await Admin.find(查询条件);
    console.log(rs);
    return res.send('ok');
    条件设置见:https://sailsjs.com/documentation/concepts/models-and-orm/query-language

更新:
    let rows=await Admin1.update({zh: 'lcjtmp6@163.com'}, {nc: '我是改过的', pwd: '333'}).fetch();
    console.log(rows);//返回一个数组,哪怕是一条数据,是被更新的数据
    return res.send('ok');

删除:
    //删除对象中某个成员delete login_data.yzm
    let rows=await Admin1.destroy({id: 5}).fetch();
    console.log(rows);//返回一个数组,哪怕是一条数据,是被删除的那条数据
    return res.send('ok');

分页:
    let rs = await Admin.find().skip(2).limit(1);
    console.log(rs);
    return res.send('ok');

统计记录数:
    let rs = await Admin.count();
    console.log(rs);//返回数字
    return res.send('ok');

排序:
    let rs = await Admin.find().sort('id desc');
    console.log(rs);
    return res.send('ok');

17、应用拦截器
  (1)在某个路由或操作中加入登录信息:如:req.session.userId={id:5,nc:'aaa'};
  注销的时候把这个session删掉
  (2)在api/policies/新建策略文件形如:isLoggedIn.js

module.exports = async function (req, res, proceed) {if (req.session.userId) {return proceed();}return res.redirect('/users/login');};

(3)在config/policiesl.js文件中修改是否应用策略
    全局方式:

      module.exports.policies = {'*': 'isLoggedIn','users/index': true,'users/login': true}

控制器方式:

   module.exports.policies = {UserController: {'*': 'isLoggedIn',//把所有的页面都拦截了'delete': 'isAdmin','login': true//允许l访问ogin}}

注:一个操作要用多个策略用[],如:['isLoggedIn', 'isAdmin']
18、文件上传

 upload: function (req, res) {req.file('image').upload(function (err, files) {if (err)return res.serverError(err);let path=files[0].fd.split('\\');path=path[path.length-1];console.log(path);//获取的文件默认放在.tmp/uploads下,这个名字应存一份到数据库return res.json({message: files.length + ' file(s) uploaded successfully!',files: files});});}

传到自定义文件夹:

    req.file('avatar').upload({dirname: require('path').resolve(sails.config.appPath, 'assets/images')},function (err, files) {if (err)return res.serverError(err);let path=files[0].fd.split('\\');path=path[path.length-1];console.log(path);//获取的文件放在assets/images下,这个名字应存一份到数据库return res.json({message: uploadedFiles.length + ' file(s) uploaded successfully!'});});

18、同时应用多个数据源
    (1).config->datastores.js

 module.exports.datastores = {default: {adapter: 'sails-mysql',url: 'mysql://root:123@localhost:3306/cqwu',},mongoDb: {adapter: 'sails-mongo',url: 'mongodb://root:@localhost:27017/shop'}};

(2).config->models.js

module.exports.models = {schema: false,//无模式,可支持多种数据源migrate: 'alter',//允许系统根据情况修改结构attributes: {// createdAt: { type: 'number', autoCreatedAt: true, },// updatedAt: { type: 'number', autoUpdatedAt: true, },id: {type: 'number', autoIncrement: true,},// id: { type: 'string', columnName: '_id' }},dataEncryptionKeys: {default: 'Yinwzamuxr9wTGiSTc7Eox31f8idirOavmpaB4UfycU='},cascadeOnDestroy: true};

(3).api->models->UserTabe.js //userTable为表或集合名称
        使用默认适配器default:

 module.exports = {attributes: {zh: {type: 'string', required: true},nc: {type: 'string', required: true},pwd: {type: 'string', required: true}}};

使用mongoDb适配器:

 module.exports = {datastore: 'mongoDb',attributes: {id: {type: 'string', columnName: '_id'},zh: {type: 'string', required: true},nc: {type: 'string', required: true},pwd: {type: 'string', required: true}},};

mongodb可以自动创建数据库,但是mysql数据库不能自动创建,需要手动创建数据库

Node 框架之sails相关推荐

  1. Node.js与Sails~方法拦截器policies

    policies sails的方法拦截器类似于.net mvc里的Filter,即它可以作用在controller的action上,在服务器响应指定action之前,对这个action进行拦截,先执行 ...

  2. 从Nest到Nesk -- 模块化Node框架的实践

    文: 达孚(沪江Web前端架构师) 本文原创,转至沪江技术 首先上一下项目地址(:>): Nest:https://github.com/nestjs/nest Nesk:https://git ...

  3. 专访死马:为什么说Egg.js是企业级Node框架

    在 7 月 6 日的 ArchSummit 架构师峰会深圳站上,Egg.js 的主要开发者不四(网名死马)将给参会者带来<企业级 Node.js Web 框架研发与落地>的分享,借此机会, ...

  4. Node框架thinkjs开发后台API

    系列文章目录 Python搭建自己的基金查看管理Web项目(一) Python搭建自己的基金查看管理Web项目(二) Python搭建自己的基金查看管理Web项目(添加预览历史数据功能) Python ...

  5. node框架LoopBack教程

    ES6的出品为JS成为企业级语言扫清障碍,与之配套的,我们需要一个真正的企业级框架.快递像一个精巧的微内核,不足以支撑起一个大项目.以下是LoopBack的一些入门知识,它是一个真正的企业级框架,随着 ...

  6. node 框架 LoopBack 教程

    本文系原创,转载请注明出处 ES6 的出品为 JS 成为企业级语言扫清障碍,与之配套的,我们需要一个真正的企业级框架.Express 像一个精巧的微内核,不足以支撑起一个大项目.以下是 LoopBac ...

  7. Node.js与Sails~Model数据模型

    回到目录 对于Sails来说,它的Model与数据库对应,不过它并没有采用目前比较流行的poco贫血模型,而是采用了类似DDD的充血模型,即它的数据实体里即有数据库字段(属性)而且还有方法,而模型里的 ...

  8. Node.js与Sails~Model和ORM的持久化

    回到目录 上一讲说了在sails里定义model及相关参数的说明,这一讲主要说一下如何将你的Model持久化到文件,关系数据库和Nosql数据库里,在持久化这点上,sails是统一管理的,它可以在/c ...

  9. 转 10 个最佳的 Node.js 的 MVC 框架

    10 个最佳的 Node.js 的 MVC 框架 oschina 发布于: 2014年02月24日 (33评) 分享到:  收藏 +322 Node.js 是一个基于Chrome JavaScript ...

  10. 10 个最佳的 Node.js 的 MVC 框架

    Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的, 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞 I/O 模型变得轻量和高效, ...

最新文章

  1. 一款腾讯UED设计的提示插件(使用教程)
  2. poj 3321 Apple Tree
  3. 外部电源、锂电池供电自动切换并自动给电池充电的电路
  4. BZOJ 1503 treap
  5. java的默认_java默认包的使用
  6. mysql随机查询多条记录表_MySQL 随机查询表中N条记录
  7. 软件工程学习进度第五周暨暑期学习进度之第五周汇总
  8. 【ACL2020】最新效果显著的关系抽取框架了解一下?
  9. Git版本控制及远程仓库的使用
  10. Log4j自定义日志级别
  11. WORD 表格中图片显示不出来?
  12. syslinux和grub引导linux,在Arch上使用Syslinux替代GRUB
  13. linux命令里的xz是干嘛的,Ubuntu中的xz命令使用
  14. 全民奇迹服务器如何修改,全民奇迹比较全的修改教程
  15. 微信小程序识别二维码
  16. cad怎样编辑标注文字?分享一个方法
  17. 飞控简析-从入门到跑路 第二章PX4的位置控制(1)
  18. APK打包的详细说明
  19. allegro封装库找不到了
  20. 雷军-我十年的程序员生涯

热门文章

  1. keras有cpu和gpu版本的区别
  2. Volatility
  3. AM中使用PML语言标注船体结构
  4. 什么农村大学生大多混得比较差-第一性原理分析
  5. scrum master_你能使我成为一个scrum master吗
  6. matlab中peaks是什么,Matlab中的peaks函数.doc
  7. “秒抢红包”锁屏勒索病毒样本分析
  8. goproxy代理软件 v10.3 轻量级高性能代理软件+链式代理+正向代理+反向代理
  9. 如何设置Macbook pro的Touch bar
  10. 仿写天猫tmall首页