小二助手(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这款优 ...
随机推荐
- pycharm设置 django模板语言
``` 参考:https://www.zhihu.com/question/65342278/answer/229993987 在setting-language&frameworks-pyt ...
- [Leetcode Week1]Longest Substring Without Repeating Characters
Longest Substring Without Repeating Characters题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/longes ...
- POJ2479(最长连续子序列和)
Maximum sum Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 37035 Accepted: 11551 Des ...
- C++类学习
一.C++类的定义 C++中使用关键字 class 来定义类, 其基本形式如下:class 类名{ public: //行为或属性 protected: //行为或属性 private: / ...
- Codeforces 106 DIV2 ACD
B表示完全看不懂..就不弄了.. E字符串先不管了.到时候系统学下字符串再处理 A #include <map> #include <set> #include <lis ...
- (十四)git操作
https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000
- ZJOI2006书架
追yql做题记录的时候做到的……一道Splay模版题…… 啊LCT写久了都有点忘了Splay了(什么奇怪的逻辑?) 其实说白了五个操作: 1. 将某元素置顶:将元素旋到根,然后将左子树合并到该元素的后 ...
- SQlServer的日期相减(间隔)datediff函数
select datediff(year, 开始日期,结束日期); --两日期间隔年 select datediff(quarter, 开始日期,结束日期); --两日期间隔季 select da ...
- linux环境下,双击直连ping私有地址时候出现Destination host unreachable 解决办法
在确保网线无故障的情况下,采取以下步骤 1.查看本机的hostname vim /etc/sysconfig/network 2.编辑/etc/hosts vim /etc/hosts 加入以下 ...
- Selenium2+python自动化71-多个浏览器之间的切换【转载】
前言 有时候一些业务的功能涉及到多个系统,需要在web系统1打开造一些数据,然后用到某些参数是动态生成的,需要调用web系统2里面的参数. 举个简单例子:在做某些业务的时候,需要手机短信验证码,我不可 ...