resjs

res.js是对AJAX的封装,用res.js调用API非常简单,回调是Promise风格的。

生成res.js

可以用flask-restaction提供的命令行工具或者 https://www.npmjs.com/package/resjs 生成res.js,两个用法一样,生成的代码也是完全一样的。

用法:

  1. usage: resjs [-h] [-d DEST] [-p PREFIX] [-n] [-m] url
  2. generate res.js for browser or nodejs
  3. positional arguments:
  4. url url of api meta
  5. optional arguments:
  6. -h, --help show this help message and exit
  7. -d DEST, --dest DEST dest path to save res.js
  8. -p PREFIX, --prefix PREFIX url prefix of generated res.js
  9. -n, --node generate res.js for nodejs, default for browser
  10. -m, --min minimize generated res.js, default not minimize

例如:

  1. resjs http://127.0.0.1:5000 -d static/res.js

res.js的用法

HTTP请求使用的是 SuperAgent,Promise使用的是 babel-plugin-transform-runtime

发出请求时会自动添加 auth token(Authorization) 请求头, 收到响应后会自动将响应头中的 auth token(Authorization) 储存在浏览器 localStorage 中。

使用res.js:

  1. // 模块加载方式(UMD)
  2. var res = require('./res.js');
  3. //或引用 res.js 文件
  4. <script type="text/javascript" src="/static/res.js"></script>

res.ajax

res.ajax 就是SuperAgent模块。

res.resource.action

用法:

  1. res.resource.action({
  2. // some data
  3. }).then(function(value){
  4. // success
  5. }).catch(function(error){
  6. // error
  7. })

例如调用Hello的API:

  1. // Hello World
  2. res.hello.get({
  3. name: 'kk'
  4. }).then(function(value){
  5. console.log(value.message);
  6. }).catch(function(error){
  7. // error
  8. })

res.xxxToken

  1. // 清除浏览器 localStorage 中的 auth token
  2. res.clearToken()
  3. // 获取浏览器 localStorage 中的 auth token
  4. var token = res.getToken()
  5. // 设置浏览器 localStorage 中的 auth token
  6. res.setToken(token)

res.config

  1. //设置请求 url 前缀,可以用来指定请求的服务器
  2. res.config.urlPrefix = 'http://127.0.0.1:5000'
  3. //设置 auth 请求头,注意要是小写字母
  4. res.config.authHeader = 'authorization'