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 list detail

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' }

注:action:访问路由控制器里的action

view:直接渲染模板文件夹的模板文件

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、连接数据库

(1).下载包

cnpm install sails-mysql --save

或者

cnpm install sails-mysql --save-exact
cnpm install sails-mongo --save

(2).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'
}
};

(3).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自动添加三个字段

4.让某个集合model有单独的模式,常用于mongodb集合

如:api/models/Normal.js

module.exports = {
schema: false,
attributes: {
}
};

14、创建model(根下)

sails generate model product 注:实际上创建表或集合

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();
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');

删除:

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/新建策略文件形如:isLogin.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 = {
'*': 'isLogin',
'users/index': true,
'users/login': true
}

控制器方式:

  module.exports.policies = {
UserController: {
'*': 'isLogin',
'delete': 'isAdmin',
'login': true
}
}

注:一个操作要用多个策略用[],如:['isLogin', '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/upload')
},
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}
},
};

19.项目移植

sails new myapp --fast

选2,

进入myapp文件夹,将原项目中自己做的部分对应考入新路径中

cd myapp
cnpm install

启动数据库

sails lift

20.前后端分离式跨源访问方式。

在api/policies/下新建策略文件如:allow.js,内容如下:

module.exports = async function (req, res, proceed) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Credentials","true");
return proceed();
}

然后再在config/policies.js文件中添加内容即可

'*': 'allow'

sails项目创建与常用基础操作总结的更多相关文章

  1. Mysql常用基础操作(备忘录)

    常常忘记mysql的一些命令行操作,甚至于说,比较复杂的sql格式记不住或忘记了,也可能根本不会考虑去记,因此,做一下汇总,当下次出现恍惚时不至于去百度挨个找,有时就是记不起来,但是只要给点药引子,立 ...

  2. Pytorch系列之常用基础操作

    各种张量初始化 创建特殊类型的tensor a = torch.FloatTensor(2,3) a = torch.DoubleTensor(2,3) ... 设置pytorch中tensor的默认 ...

  3. Pytorch系列:(一)常用基础操作

    各种张量初始化 创建特殊类型的tensor a = torch.FloatTensor(2,3) a = torch.DoubleTensor(2,3) ... 设置pytorch中tensor的默认 ...

  4. SpringBoot项目创建及入门基础

    一:快速构建springboot项目 进入https://start.spring.io/,选择相应的springboot版本,包名,项目名,依赖 图中选择web,利用tomcat服务器进行开发 sp ...

  5. CentOS7 常用基础操作

    系统目录结构了解 CentOS系统中没有磁盘的概念,一切皆文件,/目录下的的一个个文件夹目录就相当于磁盘了,这里简单记录几个常用的目录以及对应的作用: dev:Linux一切皆文件,包括硬件也进行了文 ...

  6. SPSS常用基础操作(3)——对数据资料进行整理

    在实际工作中,往往需要对取得的数据资料进行整理,使其满足特定的分析需求,下面介绍SPSS在资料整理方面的一些功能. 1.加权个案加权个案是指给不同的个案赋予不同的权重,以改变该个案在分析中的重要性.为 ...

  7. SPSS常用基础操作(2)——连续变量离散化

    首先说一下什么是离散化以及连续变量离散化的必要性. 离散化是把无限空间中无限的个体映射到有限的空间中去,通俗点讲就是把连续型数据切分为若干“段”,也称bin,离散化在数据分析中特别是数据挖掘中被普遍采 ...

  8. SPSS常用基础操作(1)——变量分组

    有时我们需要对数据资料按照某个规则进行归组,如 在上述资料中,想按照年龄进行分组,30岁以下为组1,30-40岁为组2,40岁以上为组3 有两种方法可以实现: 1.使用计算变量功能 <1> ...

  9. Elasticsearch常用基础操作

    1.获得集群中的节点列表: curl 'localhost:9200/_cat/nodes?v' 2.获得所有索引: curl 'localhost:9200/_cat/indices?v' 3.创建 ...

随机推荐

  1. Scripting web services

    A process performed on a server includes configuring the server to enable script for a Web service t ...

  2. [C 语言]判断某文件是文件夹还是文件

    #include <sys/stat.h> #include <stdio.h> int _tmain(int argc, _TCHAR* argv[]){ char* fil ...

  3. uwp - 获取当前屏幕宽高/应用宽高

    原文:uwp - 获取当前屏幕宽高/应用宽高 public static Size GetScreen() { var applicationView = ApplicationView.GetFor ...

  4. C#或者WPF中让某个窗体置顶

    原文:C#或者WPF中让某个窗体置顶 前记:在工作中有个需求,要求不管到那个界面,我必须让一个浮动条(其实是个窗体)置顶. 我用wpf,因为有之前有好几个界面已经设置成topmost了,所以在这几个界 ...

  5. 存储过程和输出分辨率表菜单JSON格式字符串

    表的结构,如以下: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo] ...

  6. 【值转换器】 WPF中Image数据绑定Icon对象

    原文:[值转换器] WPF中Image数据绑定Icon对象        这是原来的代码:        <Image Source="{Binding MenuIcon}" ...

  7. C和指针 (pointers on C)——第十二章:利用结构和指针

    第十二章 利用结构和指针 这章就是链表.先单链表,后双向链表. 总结: 单链表是一种使用指针来存储值的数据结构.链表中的每一个节点包括一个字段,用于指向链表的下一个节点. 有一个独立的根指针指向链表的 ...

  8. 【剑指Offer学习】【面试题4 : 替换空格】

    题目: 请实现一个函数,把字符串中的每个空格替换成"%20",例如“We are happy.”,则输出“We%20are%20happy.”. 以下代码都是通过PHP代码实现. ...

  9. XF堆栈布局

    <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http:/ ...

  10. VS2012发布到XP平台

    默认情况下,你的VS2012工程发布后,在XP下运行会出现提示“not a valid win32 application”. 微软推出了Visual Studio 2012 update 1可以支持 ...