小二助手(react应用框架)-http访问
浏览地址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访问的更多相关文章
- 小二助手-react.js分块加载
小二助手在线演示地址:http://118.25.217.253:8000 账号test 密码123 小二助手是用material-ui开发的,感觉国内使用的人数不是特别多,所以创建了一个qq交流群 ...
- 13个精选的React JS框架
如果你正在使用 React.js 或 React Native 创建用户界面,可以试一试本文推荐的这些框架. React.js 和 React Native 是流行的用户界面(UI)开发平台,且都是开 ...
- FoxOne---一个快速高效的BS框架--数据访问(Dao)
FoxOne---一个快速高效的BS框架--(1) FoxOne---一个快速高效的BS框架--(2) FoxOne---一个快速高效的BS框架--(3) FoxOne---一个快速高效的BS框架-- ...
- React 等框架使用 index 做 key 的问题
React 等框架使用 index 做 key 的问题 假如有两个树,一个是之前,一个是更变之后,我们抽象成两种可能性. 插入内容在最后 插入内容在最前 关于插在中间,原理一样,就不阐述. 使用 ul ...
- UmiJS可插拔的企业级 react 应用框架,配合ant-design-pro使用
入门非常简单 # 安装 $ yarn global add umi # 或者 npm install -g umi # 新建应用 $ mkdir myapp && cd myapp # ...
- React Native框架如何白盒测试-HIPPY接口测试架构篇
本文转载自腾讯TMQ团队 ,侵权删. 1.开天辟地 Hippy是什么呢?简单点,能用JavaScript来写Android和iOS应用的框架, 类似业界的React Native. 好吧,我们还是严谨 ...
- react axios 跨域访问一个或多个域名
1.react + axios 跨域访问一个域名 配置非常简单,只需要在当前的 package.json 文件里面配置: "proxy":"http://iot-demo ...
- 小二助手(react应用框架)-概述
时间想学习一个前端框架,原因是这样的,我本身是做游戏的,但是自己对前端web比较感兴趣. 然后我就选择自己学哪个框架,Angular.react.vue 最后选择了react,选择的理由就不说了 那做 ...
- Weex和React Native框架对比与选择
工作原理 大致基本类同,JS-Native桥和前端渲染框架,只是使用框架技术不一样: Weex 阿里内部早期研发的一个通过 JSON 数据描述 native 渲染的项目WeApp以及Vue.js这款优 ...
随机推荐
- ubuntu设置默认python版本
原文:https://www.cnblogs.com/johnny1024/p/8400511.html ··· ubuntu 16.04本身是自带python的,他本身是自带2.X和3.X,两个版本 ...
- 转:Android 调试桥(adb)是多种用途的工具
转自:http://my.oschina.net/xuwa/blog/1574 Android 调试桥(adb)是多种用途的工具,该工具可以帮助你你管理设备或模拟器 的状态. 可以通过下列几种方法加入 ...
- UVA 10303 How Many Trees? (catlan)
刚开始没看出时卡特兰数列.直接套高精度版 #include <map> #include <set> #include <list> #include <cm ...
- 智联招聘的python岗位数据结巴分词(二)
上次获取第一次分词之后的内容了 但是数据数据量太大了 ,这时候有个模块就派上用场了collections模块的Counter类 Counter类:为hashable对象计数,是字典的子类. 然后使用m ...
- ApplicationCommands 应用程序常见命令
ApplicationCommands用于表示应用程序程序员经常遇到的常见命令,类似于ctrl+c 在WPF中,许多控件都自动集成了固有的命令集.比如文本框TextBox就提供了复制(Copy),粘贴 ...
- 《Java编程思想》笔记 第七章 复用类
1.组合 将其他类的对象引用置于新的类中. 3.继承 extends 从已知的一个类中派生出新的一个类,叫子类.子类实现了父类所有 非私有化 非静态 的属性和方法,并能根据自己的实际需求扩展出新的行为 ...
- 安装smartmontool报错:libc6-dev : 破坏:
https://blog.csdn.net/weixin_38705903/article/details/81947717
- mimikatz-域密码获取神器
mimikatz是一个法国人写的轻量级调试器.出众之处在于其可以直接从 lsass.exe 里猎取windows处于active状态账号明文密码,非常强大. 在网上找了一些相关的文章自己的一点总结吧 ...
- CvScalar
CvScalar定义可存放1—4个数值的数值,其结构如下. typedef struct CvScalar{ double val[4];}CvScalar; ----------------- ...
- CF 990C. Bracket Sequences Concatenation Problem【栈/括号匹配】
[链接]:CF [题意]: 给出n个字符串,保证只包含'('和')',求从中取2个字符串链接后形成正确的括号序列的方案数(每个串都可以重复使用)(像'()()'和'(())'这样的都是合法的,像')( ...