小二助手(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这款优 ...
随机推荐
- TCP的三次握手和四次挥手+TCP和UDP的区别
TCP的三次握手: LISTEN:表示服务器端的某个socket处于监听状态,可以接收连接了. SYN_SENT:当客户端SOCKET执行connect连接时,它首先发送syn报文,随即会进入到此状态 ...
- H5智能表单
表单 keygen元素的作用是提供一种验证用户的可靠方法 datalist 元素规定输入域的选项列表 output元素用于不同类型的输出,比如计算或脚本输出 智能表单 input 新增type值 em ...
- [ 总结 ] Linux kickstart 无人值守安装系统构建过程
环境:Vmare + Linux虚拟机 注意:网卡桥接
- Java虚拟机栈 和 方法区 的联系
1.Java虚拟机栈 java方法执行时的内存模型 1.1 栈帧 每个方法都会在虚拟机栈中创建一个对应的栈帧,用于存储局部变量表,操作数栈,动态链接,方法出口等信息. 一个方法的调用到结束就对应这一个 ...
- 使用vscode开发调试.net core应用程序并部署到Linux跨平台
使用VS Code开发 调试.NET Core RC2应用程序,由于.NET Core 目前还处于预览版. 本文使用微软提供的示例进行开发及调试. https://github.com/aspnet/ ...
- 零基础如何学习 Web 安全?(转)
在网上看了一篇文章<零基础如何学习 Web 安全?>,虽然很多东西的都不是很懂,感觉挺好的copy过来,慢慢消化: 文章地址:https://www.zhihu.com/question/ ...
- mysql对表的操作
创建表 简单的方式 CREATE TABLE person ( number INT(11), name VARCHAR(255), birthday DATE ); 或者是 CREATE TABLE ...
- DNS无响应
无语,运行某某大品牌的杀毒软件后,无法上网,window检查后是DNS服务器无响应. 开始>运行>输入"netsh winsock reset" 然后重启电脑. pi ...
- codevs 1643 线段覆盖 3
1643 线段覆盖 3 时间限制: 2 s 空间限制: 256000 KB 题目等级 : 黄金 Gold 题解 题目描述 Description 在一个数轴上有n条线段,现要选取其中 ...
- 【二分答案】【分块答案】【字符串哈希】【set】bzoj2946 [Poi2000]公共串
我们二分/分块枚举答案x,暴力把除了最短的字符串以外的其他字符串的x长度子串哈希搞出来,分别扔到set里. 然后暴力枚举最短的字符串的x长度字串,查看是否在全部的set里出现过. #include&l ...