改造Sailsjs解决Typescript支持,跨域,Swagger,MySql连接等问题

TypeScript 支持

1.项目下安装TS

npm install typescript ts-node --save
npm install @types/node --save
npm install @types/express --save

2.初始化tsconfig配置文件,这会在项目下生成一个tsconfig.json的文件

npx tsc --init

3.配置tsconfig.json,更多的配置可以查看TS官网文档

{
  "compilerOptions": {   
    "target": "es2016",           
    "module": "commonjs",     
    "paths": {
      "@/*": ["./api/*"],      
      "@/typing/*": ["./typing/*"],
    },
    "allowJs": true,  
    "esModuleInterop": true,     
    "forceConsistentCasingInFileNames": true,   
    "strict": true,    
    "suppressImplicitAnyIndexErrors": true,      
    "skipLibCheck": true         
  },
  "include": [
    "api/**/*",
    "api/*",
    "typing/**/*",
    "typing/*",    
  ],
  "exclude": ["node_modules", "build", "dist", "scripts", ".tmp/*"]
}

4.Add the following line at the top of your app’s app.js file:

require('ts-node/register');

5.Start your app with node app.js instead of sails lift.

TypeScript 问题

1、tsconfig.json
tsconfig.json文件在VsCode编译器里面标红,提示错误如下:
报错内容
JSON schema for the TypeScript compiler’s configuration file
无法写入文件“xxxx/xxx.js”,因为它会覆盖输入文件。ts
解决方法:
在tsconfig.json文件的配置中添加配置,保存配置文件后重启vscode就可以了

"compilerOptions": {
   "outDir":"dist"
}

2、tsc 编译并测试(需要依赖tsconfig.json)

tsc -p .  //-p 指明tsconfig.json的文件路径 "."表示配置文件在当前目录
node dist/test/test.js //dist是tsconfig.json里面指定outdir的目录,test/test.js是要测试的js文件

3、typescript 用索引访问对象问题
有时候需要用object[key]的方式访问未知对象key的属性,类似下面的代码

for (const key in obejct) {
	// 处理...
	obejct[key]
	....
}

在ts里面,如果是any类型的时候,会报错如下:
元素隐式具有 “any“ 类型,因为类型为 “string“ 的表达式不能用于索引类型 “Object“。 在类型 “Object“ 上找不到具有类型为 “string“ 的参数的索引签名
解决方法是:
在tsconfig.json中compilerOptions里面新增忽略的代码,如下所示,添加后则不会报错

"suppressImplicitAnyIndexErrors": true

设置跨域

config/security.js

  cors: {
    allRoutes: true,
    allowRequestMethods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
    allowOrigins: '*',
    allowCredentials: false
  },

MySql连接问题

MySQL8.0版本的加密方式和MySQL5.0不一样,由于mysql8.0以上加密方式,Node还不支持。所以Sails连接MySql会有问题。修改调整MySql服务器的加密方式
1、更改加密方式

ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;

2、修改密码,以下示例中 123456为新密码 。

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';

3、刷新:

FLUSH PRIVILEGES;

4、重启服务
进入windows服务管理,重启MySql80服务

创建api

1、config/routes.js里面添加路由示例

 'POST /api/login/account': { action: 'users/check' },
  'GET /api/currentUser': { action: 'users/curUser' },

2、api/controllers里面添加路由示例
添加AmisController.js
代码如下:

/**
 * AmisController
 *
 * @description :: Server-side actions for handling incoming requests.
 * @help        :: See https://sailsjs.com/docs/concepts/actions
 */
const crudDataTable = [
  {
    engine: 'Trident - 81dkop',
    browser: 'Internet Explorer 4.0',
    platform: 'Win 95+',
    version: '4',
    grade: 'X',
    badgeText: '默认',
    id: 1,
  },
  {
    engine: 'Trident - hrandik',
    browser: 'Internet Explorer 5.0',
    platform: 'Win 95+',
    version: '5',
    grade: 'C',
    badgeText: '危险',
    id: 2,
  },
  {
    engine: 'Trident - yyoclb',
    browser: 'Internet Explorer 5.5',
    platform: 'Win 95+',
    version: '5.5',
    grade: 'A',
    id: 3,
  },
  {
    engine: 'Trident - 48ajln',
    browser: 'Internet Explorer 6',
    platform: 'Win 98+',
    version: '6',
    grade: 'A',
    id: 4,
  },  
  {
    engine: 'Other browsers - i3elyt',
    browser: 'All others',
    platform: '-',
    version: '-',
    grade: 'U',
    id: 171,
  },
];
const genList = (current, pageSize) => {
  let resList = [];
  const start = (current - 1) * pageSize;
  const end = start + pageSize;
  resList = crudDataTable.slice(start, end);
  return resList;
};
module.exports = {


  /**
   * `AmisController.crudDemo()`
   */
  crudDemo: async function (req, res) {
    let page = 1;
    let pagesize = 10;
    if (req.query.page) { page = parseInt(String(req.query.page)); }
    if (req.query.perPage) { pagesize = parseInt(String(req.query.perPage)); }
    const resData = {
      status: 0,
      msg: 'ok',
      data: {
        count: 171,
        rows: genList(page, pagesize),
      },
    };
    res.send({ data: resData });
  },

  /**
   * `AmisController.crudNew()`
   */
  crudNew: async function (req, res) {
    const resData = {
      status: 0,
      msg: '新增成功',
      data: null,
    };
    res.send({ data: resData });
  },

  /**
   * `AmisController.crudDelete()`
   */
  crudDelete: async function (req, res) {
    const resData = {
      status: 0,
      msg: '删除成功',
      data: null,
    };
    res.send({ data: resData });
  }

};

设置端口

config/local.js

module.exports = {
  port:1898
  // Any configuration settings may be overridden below, whether it's built-in Sails
  // options or custom configuration specifically for your app (e.g. Stripe, Sendgrid, etc.)
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值