浏览地址http://118.25.217.253:4000 账号test密码123   qq讨论群:836719189

要写这个系统,就需要数据来源,让我们先来看看如果通过客户端调用服务端api拿到数据

http访问服务端api我直接使用了XMLHttpRequest,并没用使用其它第三方组件。

用户通过登录界面登录获得token,把token写入到cookie,后面的api调用从cookie取出token写入到httpheader,这样登录后的每次请求都是带token的,都是安全调用。

见下面的HttpService类:

import Cookie from './cookie'

export default class HttpService {
static query(config) {
config = config || {};
var params = HttpService.formatParams(config.data); var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
var status = request.status;
if (status >= 200 && status < 300) {
var res = JSON.parse(request.responseText);
config.success && config.success(res);
} else {
//return config.fail && config.fail(status);
Cookie.delete('token');
window.location='/';
}
}
};
request.open('GET', config.url + "?" + params, true);
request.setRequestHeader("Authorization", 'Bearer '+Cookie.get('token'));
request.send(null);
} static jsonp(config) {
config = config || {}; var params = HttpService.formatParams(config.data);
var Scrip=document.createElement('script');
Scrip.src = config.url + "?" + params + "&jsoncallback=HttpService.jsonpCallback";
this.callback = config.success; document.body.appendChild(Scrip);
} static jsonpCallback(e) {
this.callback(e);
} static save(config) {
config = config || {}; var params = HttpService.formatParams(config.data);
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
var status = request.status;
if (status >= 200 && status < 300) {
var res = JSON.parse(request.responseText);
console.log(res);
config.success && config.success(res);
} else {
//config.fail && config.fail(status);
Cookie.delete('token');
window.location='/';
}
}
};
request.open("POST", config.url, true);
request.setRequestHeader("Authorization", 'Bearer '+Cookie.get('token'));
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(params);
} static uploadFile(cfg) {
var config = cfg || {};
var xhr;
var fileObj = config.file; // js 获取文件对象
var url = config.url; // 接收上传文件的后台地址
var form = new FormData(); // FormData 对象
form.append(config.name, fileObj); // 文件对象
xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
xhr.open("post", url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var status = xhr.status;
if (status >= 200 && status < 300) {
var res = JSON.parse(xhr.responseText);
console.log(res);
config.success && config.success(res);
} else {
config.fail && config.fail(status);
}
}
};
xhr.send(form); //开始上传,发送form数据
} static formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("v=" + Math.random()).replace(".", ""));
return arr.join("&");
}
}

然后封装了两个常用的调用方法,api调用时打开数据加载提示,加载出错提示错误信息,加载成功执行成功事件。

static httpsave(url, data, func, showloding) {
if (showloding) {
CrossComponentAccess.showDataLoading();
}
HttpService.save({
url: this.ApiUrl + url,
data: data,
success: res => {
if (showloding) {
CrossComponentAccess.hideDataLoading();
}
if (res.succeed) {
func(res);
}
else {
CrossComponentAccess.showPromptDialog(res.body);
}
}
});
} static httpquery(url, data, func, showloding) {
if (showloding) {
CrossComponentAccess.showDataLoading();
}
HttpService.query({
url: this.ApiUrl + url,
data: data,
success: res => {
if (showloding) {
CrossComponentAccess.hideDataLoading();
}
if (res.succeed) {
func(res);
}
else {
CrossComponentAccess.showPromptDialog(res.body);
}
}
});
}

上面两个方法里面的CrossComponentAccess类,通过事件通知调用显示数据加载提升和操作完的提示。

所有的对服务端的api访问都是在下面ServerApi这个类里面的。调用成功后使用通知中心EventNotificationCenter把数据广播出去

import HttpService from './http-service';
import EventNames from '../config/event-names'
import EventNotificationCenter from './event-notification-center'
import CrossComponentAccess from './cross-component-access' export default class ServerApi {
static ApiUrl = "http://118.25.217.253:8010";
//static ApiUrl = "http://localhost:53418";
//static ApiUrl = "http://118.25.217.253:4010"; static httpsave(url, data, func, showloding) {
if (showloding) {
CrossComponentAccess.showDataLoading();
}
HttpService.save({
url: this.ApiUrl + url,
data: data,
success: res => {
if (showloding) {
CrossComponentAccess.hideDataLoading();
}
if (res.succeed) {
func(res);
}
else {
CrossComponentAccess.showPromptDialog(res.body);
}
}
});
} static httpquery(url, data, func, showloding) {
if (showloding) {
CrossComponentAccess.showDataLoading();
}
HttpService.query({
url: this.ApiUrl + url,
data: data,
success: res => {
if (showloding) {
CrossComponentAccess.hideDataLoading();
}
if (res.succeed) {
func(res);
}
else {
CrossComponentAccess.showPromptDialog(res.body);
}
}
});
} static login(loginName, password) {
this.httpsave('/User/Login', { loginName: loginName, password: password }, res => {
EventNotificationCenter.send(EventNames.OnLoginBack, { uid: res.body.user.id, uname: res.body.user.loginName, uroles: res.body.user.roles, token: res.body.token });
}, true);
} static listDataPage(apicontroller, searchText, currentPage, pageSize, urlpars) {
this.httpquery('/' + apicontroller + '/List', { searchText: searchText, pageIndex: currentPage, pageSize: pageSize, urlpar: urlpars }, res => {
EventNotificationCenter.send(apicontroller + "_List", res.body);
if (apicontroller === "Knowledge") {
EventNotificationCenter.send(EventNames.KnowledgeCategoryMenu, res.body.category);
}
if (apicontroller === "KnowledgeCategory") {
EventNotificationCenter.send(EventNames.KnowledgeCategoryMenu, res.body.dataSource);
}
if (apicontroller === "FlowAccount") {
EventNotificationCenter.send(EventNames.BankAccountMenu, res.body.allBankAccount);
}
if (apicontroller === "BankAccount") {
EventNotificationCenter.send(EventNames.BankAccountMenu, res.body.dataSource);
}
if (apicontroller === "AdvertisingCompany") {
EventNotificationCenter.send(EventNames.ADMenu, res.body.dataSource);
}
if (apicontroller === "AdvertisingSpace") {
EventNotificationCenter.send(EventNames.ADMenu, res.body.company);
}
if (apicontroller === "Task") {
EventNotificationCenter.send(EventNames.TaskMenu, res.body.allExecutor);
}
}, false);
} static deleteDataPage(apicontroller, ids) {
this.httpsave('/' + apicontroller + '/Delete', { ids: ids }, res => {
EventNotificationCenter.send(apicontroller + "_Delete", res.body);
}, true);
} static saveDataPage(apicontroller, data) {
this.httpsave('/' + apicontroller + '/Save', data, res => {
EventNotificationCenter.send(apicontroller + "_Save", res.body);
}, true);
} static infoDataPage(apicontroller, id, par) {
this.httpquery('/' + apicontroller + '/Get', { id: id, par: par }, res => {
EventNotificationCenter.send(apicontroller + "_Get", res.body);
}, true);
} static listFlowAccount(urlpars, project, flowCategory, beginTime, endTime, currentPage, pageSize) {
if (beginTime !== undefined && beginTime !== "" && endTime !== undefined && endTime !== "") {
this.httpquery('/FlowAccount/List', { urlpar: urlpars, project: project, flowCategory: flowCategory, beginTime: beginTime, endTime: endTime, pageIndex: currentPage, pageSize: pageSize }, res => {
EventNotificationCenter.send("FlowAccount_List", res.body);
EventNotificationCenter.send(EventNames.BankAccountMenu, res.body.allBankAccount);
}, false);
}
else {
this.httpquery('/FlowAccount/List', { urlpar: urlpars, project: project, flowCategory: flowCategory, pageIndex: currentPage, pageSize: pageSize }, res => {
EventNotificationCenter.send("FlowAccount_List", res.body);
EventNotificationCenter.send(EventNames.BankAccountMenu, res.body.allBankAccount);
}, false);
}
} static listTask(excutorID, projectID, taskStepID, currentPage, pageSize, isClosed) {
this.httpquery('/Task/List', { excutorID: excutorID, projectID: projectID, taskStepID: taskStepID, isClosed: isClosed, pageIndex: currentPage, pageSize: pageSize }, res => {
EventNotificationCenter.send("Task_List", res.body);
EventNotificationCenter.send(EventNames.TaskMenu, res.body.allExecutor);
}, false);
} static closeTask(ids) {
this.httpsave('/Task/Close', { ids: ids }, res => {
EventNotificationCenter.send("Task_Close", res.body);
}, true);
}
}

这章http访问里,涉及到Cookie和通知中心EventNotificationCenter在下一章介绍。

小二助手(react应用框架)-http访问的更多相关文章

  1. 小二助手-react.js分块加载

    小二助手在线演示地址:http://118.25.217.253:8000  账号test 密码123 小二助手是用material-ui开发的,感觉国内使用的人数不是特别多,所以创建了一个qq交流群 ...

  2. 13个精选的React JS框架

    如果你正在使用 React.js 或 React Native 创建用户界面,可以试一试本文推荐的这些框架. React.js 和 React Native 是流行的用户界面(UI)开发平台,且都是开 ...

  3. FoxOne---一个快速高效的BS框架--数据访问(Dao)

    FoxOne---一个快速高效的BS框架--(1) FoxOne---一个快速高效的BS框架--(2) FoxOne---一个快速高效的BS框架--(3) FoxOne---一个快速高效的BS框架-- ...

  4. React 等框架使用 index 做 key 的问题

    React 等框架使用 index 做 key 的问题 假如有两个树,一个是之前,一个是更变之后,我们抽象成两种可能性. 插入内容在最后 插入内容在最前 关于插在中间,原理一样,就不阐述. 使用 ul ...

  5. UmiJS可插拔的企业级 react 应用框架,配合ant-design-pro使用

    入门非常简单 # 安装 $ yarn global add umi # 或者 npm install -g umi # 新建应用 $ mkdir myapp && cd myapp # ...

  6. React Native框架如何白盒测试-HIPPY接口测试架构篇

    本文转载自腾讯TMQ团队 ,侵权删. 1.开天辟地 Hippy是什么呢?简单点,能用JavaScript来写Android和iOS应用的框架, 类似业界的React Native. 好吧,我们还是严谨 ...

  7. react axios 跨域访问一个或多个域名

    1.react + axios 跨域访问一个域名 配置非常简单,只需要在当前的 package.json 文件里面配置: "proxy":"http://iot-demo ...

  8. 小二助手(react应用框架)-概述

    时间想学习一个前端框架,原因是这样的,我本身是做游戏的,但是自己对前端web比较感兴趣. 然后我就选择自己学哪个框架,Angular.react.vue 最后选择了react,选择的理由就不说了 那做 ...

  9. Weex和React Native框架对比与选择

    工作原理 大致基本类同,JS-Native桥和前端渲染框架,只是使用框架技术不一样: Weex 阿里内部早期研发的一个通过 JSON 数据描述 native 渲染的项目WeApp以及Vue.js这款优 ...

随机推荐

  1. 用树莓派做FTP服务器

    我为了传输文件方便,所以先简单的做了一个匿名ftp服务器 首先要下载ftp服务器软件 输入 sudo apt-get install vsftpd 安装vsftp 然后编辑 /etc/vsftp.co ...

  2. Linux ssh的使用

    1.查看SSH客户端版本 有的时候需要确认一下SSH客户端及其相应的版本号.使用ssh -V命令可以得到版本号.需要注意的是,Linux一般自带的是OpenSSH: 下面的例子即表明该系统正在使用Op ...

  3. LeetCode 192:Reverse Bits

    Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in ...

  4. UVALIVE 2686 Stargates

    尼玛真深坑合时p[x] = y 就RE,p[y] = x 就AC . #include <map> #include <set> #include <list> # ...

  5. JS实现上下左右对称的九九乘法表

    JS实现上下左右对称的九九乘法表 css样式 <style> table{ table-layout:fixed; border-collapse:collapse; } td{ padd ...

  6. Centos 7.2 双网卡绑定之踩坑

    线上服务器,安装centos7.2 x64最小化安装,需要做链路聚合,双网卡绑定.在centos 6.x 和 centos 7上测试都OK,于是直接开搞. 说明下,以下环境是在虚拟机中实现的: 系统: ...

  7. 【C++】指针和new相关

    看黄邦勇帅的笔记. 指针和new之前觉得已经掌握的很好了,可是看了资料还是get到了新知识.记录一下. 1.指针只支持 4 种算术运算符:++,――,+,-.指针只能与整数加减.指针运算的原则是:每当 ...

  8. ccf-I’m stuck!

      给定一个R行C列的地图,地图的每一个方格可能是'#', '+', '-', '|', '.', 'S', 'T'七个字符中的一个,分别表示如下意思: '#': 任何时候玩家都不能移动到此方格: ' ...

  9. MyBatis入门实例 ——Mapper.xml(zz)

    <?xml version="1.0" encoding="UTF-8" ?>    <!DOCTYPE mapper        PUBL ...

  10. Codeforces 702D Road to Post Office(模拟 + 公式推导)

    题目链接:http://codeforces.com/problemset/problem/702/D 题意: 一个人要去邮局取东西,从家到达邮局的距离为 d, 它可以选择步行或者开车,车每走 k 公 ...