Egg.js学习与实战系列 · jsonp接口的封装使用

jsonp作为前端跨域的一种解决方案,不用像配置nginx那样做一系列的反向代理转发,返回的数据结构也比较严谨,使用起来简单,方便。本篇就讲讲jsonp接口在Egg框架中的封装与使用。

Egg+Jsonp

下载 egg-jsonp 插件

egg-jsonp 是用于 jsonp 支持的 Egg 插件。

npm i -S egg-jsonp 

配置

  • config/plugin.js
// {app_root}/config/plugin.js

exports.jsonp = {
  enable: true,
  package: 'egg-jsonp',
};
  • config/config.default.js
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  config.jsonp = {
    limit: 100,
    // callback: [ '_callback', 'callback' ],
    // csrf: true,
    // whiteList: [
    // 'localhost:4000/',
    // '127.0.0.1:4000/',
    // ],
  };
  return {
    ...config,
  }
}

配置解释:

  • callback:jsonp回调方法key值,默认为 [ '_callback', 'callback' ]
  • csrf:是否启用 csrf 防御检查。默认为 false
  • limit:回调方法名的最大长度,默认为 50
  • whiteList:请求referrer的白名单。类型可以是String、Array、RegExp。
    * 字符串:{whiteList : ‘.test.com’}
    * 正则:{whiteList : / ^ https?: / / test.com / /},如果 whiteList 的类型是正则,referrer 必须匹配 whiteList,注意 first^last /
    * 数组:{whiteList : [ ‘.foo.com’ , ‘.bar.com’ ]}

controller

// app/controller/jsonp/index.js
'use strict';

const Controller = require('egg').Controller;

class JsonpController extends Controller {

  async list() {
    const { ctx } = this;
    ctx.body = [
      {
        id: 1,
        name: '天問', 
      },
      {
        id: 2,
        name: '天问', 
      },
      {
        id: 3,
        name: 'Tiven', 
      },
    ];
  }

}

module.exports = JsonpController;

router

// app/router.js

module.exports = app => {
  const { router, controller } = app;
  const jsonp = app.jsonp();
  
  router.get('/api/v1/jsonp/list', jsonp, controller.jsonp.index.list);
};

前端页面调用

function getList(res) {
  if (!res) return
  // jsonp接口返回的数据
  // do ...
  console.log(res)
}
let script = document.createElement('script')
script.src = `http://127.0.0.1:7001/api/v1/jsonp/list?callback=getList&v=${Date.now()}`
document.body.appendChild(script)
  • 打开控制台的network可以查看jsonp返回的数据结构:
/**/ typeof getList === 'function' && getList([{ "id": 1, "name": '天問'}, { "id": 2,"name": '天问'},{"id": 3, "name": 'Tiven'}]);

参考文档:

  • https://github.com/eggjs/egg-jsonp

《Egg.js学习与实战》系列


欢迎访问:个人博客地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值