rewrite ajax

This commit is contained in:
zuiidea
2016-09-17 16:17:20 +08:00
parent 0740f644a4
commit c204c95bba
6 changed files with 84 additions and 134 deletions
+13 -14
View File
@@ -1,30 +1,29 @@
import React from 'react';
import {Icon, Menu, Dropdown} from 'antd';
import globalConfig from 'config';
import { Icon, Menu, Dropdown } from 'antd';
import { config, ajax, signOut } from '../../utils/lib.js'
import './index.less';
const SubMenu = Menu.SubMenu; // 为了使用方便
/**
* 定义Header组件, 包括登录/注销的链接, 以及一些自定义链接
*/
class Header extends React.Component {
const SubMenu = Menu.SubMenu;
let Header = React.createClass({
signOut(){
ajax({
url:config.user.signOut
})
},
render() {
return (
<div className='ant-layout-header'>
{/*定义header中的菜单*/}
<Menu className="header-menu" mode="horizontal">
<SubMenu title={<span><Icon type="user" />{this.props.userName}</span>}>
<Menu.Item key="logout">
<a href={`${globalConfig.getAPIPath()}${globalConfig.login.logout}`}>注销</a>
<Menu.Item key="signOut">
<a onClick={this.signOut}>注销</a>
</Menu.Item>
</SubMenu>
</Menu>
</div>
);
}
})
}
export default Header;
module.exports = Header
+6 -86
View File
@@ -5,97 +5,17 @@ module.exports = {
logoText:'Ant Design',
debug: true,
logLevel: 'debug',
needLogin:false,
needLogin:true,
api: {
host: 'http://localhost',
host: 'http://localhost:8080',
path: '/api',
timeout: 15000,
},
login: {
getCurrentUser: '/getCurrentUser',
sso: '',
validate: '/login',
logout: '/logout',
},
/**
* 是否要跨域请求
*
* @returns {boolean}
*/
isCrossDomain: function () {
if (this.api.host && this.api.host !== '') {
return true;
} else {
return false;
}
},
/**
* 是否单点登录
*
* @returns {boolean}
*/
isSSO: function () {
if (this.login.sso && this.login.sso !== '') {
return true;
} else {
return false;
}
},
/**
* 获得api请求的路径
*
* @returns {*}
*/
getAPIPath: function () {
if (this.tmpApiPath) { // 缓存
return this.tmpApiPath;
}
const paths = [];
// js的字符串处理真是麻烦
if (this.isCrossDomain()) {
// 去除结尾的'/'
const tmp = this.api.host;
let index = tmp.length - 1;
// 如果超出指定的 index 范围,charAt返回一个空字符串
while (tmp.charAt(index) === '/') {
index--;
}
if (index < 0)
paths.push('');
else
paths.push(tmp.substring(0, index + 1));
} else {
paths.push('');
}
if (this.api.path) {
const tmp = this.api.path;
let begin = 0;
let end = tmp.length - 1;
while (tmp.charAt(begin) === '/') {
begin++;
}
while (tmp.charAt(end) === '/') {
end--;
}
if (begin > end)
paths.push('');
else
paths.push(tmp.substring(begin, end + 1));
} else {
paths.push('');
}
const tmpApiPath = paths.join('/');
this.tmpApiPath = tmpApiPath;
return tmpApiPath;
user: {
info: '/getInfo',
signIn: '/signIn',
signOut:'/signOut',
},
};
+1 -1
View File
@@ -8,7 +8,7 @@
</head>
<body>
<div id="view"></div>
<div id="view" style="height:100%"></div>
<script src="http://localhost:8080/webpack-dev-server.js"></script>
</body>
</html>
+42 -1
View File
@@ -4,8 +4,49 @@ import reqwest from 'reqwest'
import './lib.less'
function ajax(data){
if(config.debug){
console.log(data);
setTimeout(function(){
if(data.url==config.user.info){
if(localStorage.getItem("username")&&localStorage.getItem("username")=="guest"&&
localStorage.getItem("password")&&localStorage.getItem("password")=='guest'){
data.success({
message:'登录成功',
isSuccess:true,
userName:"guest"
})
}else {
data.success({
message:'获取信息成功',
isSuccess:false,
userName:"guest"
})
}
}else if (data.url==config.user.signIn) {
if(data.complete){
data.complete()
}
if(data.data.username=='guest'&&data.data.password=='guest'){
localStorage.setItem("username","guest")
localStorage.setItem("password","guest")
data.success({
message:'登录成功',
isSuccess:true,
userName:"guest"
})
}else {
data.success({
message:'密码错误',
isSuccess:false
})
}
}else if (data.url==config.user.signOut) {
localStorage.removeItem("username")
localStorage.removeItem("password")
location.reload()
}
},500)
}else {
reqwest(data)
}
+11 -22
View File
@@ -27,36 +27,25 @@ const App = React.createClass({
}
},
componentDidMount() {
const _this = this
if (!this.state.login) {
const hide = message.loading('正在获取用户信息...', 0)
ajax.get(`${config.getAPIPath()}${config.login.getCurrentUser}`).end((err, res) => {
if (ajax.isSuccess(res) && !config.debug) {
hide()
this.loginSuccess(res.body.data)
} else {
if (config.isSSO()) {
hide()
logger.debug('not login, redirect to SSO login page')
const redirect = encodeURIComponent(window.location.href)
window.location.href = `${config.login.sso}${redirect}`
const loading = message.loading('正在获取用户信息...', 0)
ajax({
url: config.user.info,
success: function (result) {
if (result.isSuccess) {
loading()
_this.loginSuccess(result.userName)
} else {
hide()
message.error('获取用户信息失败, 请重新登录')
logger.debug('not login, redirect to Login component')
this.setState({
loading: false,
login: false,
})
loading()
_this.setState({loading: false})
}
}
})
}
},
loginSuccess(name, showMsg) {
loginSuccess(name) {
logger.debug('callback logingSuccess, name = %s', name)
if (showMsg) {
message.success('登录成功')
}
this.setState({
loading: false,
login: true,
+11 -10
View File
@@ -21,17 +21,18 @@ let SignIn = React.createClass({
return
}
_this.setState({ loading: true })
ajax.post(`${config.getAPIPath()}${config.login.validate}`)
.type('form').send(values).end((err, res) => {
_this.setState({ loading: false })
if (ajax.isSuccess(res)) {
if (this.props.loginSuccess) {
this.props.loginSuccess(res.body.data, true)
} else {
message.info(`登录成功, 用户名: ${res.body.data}`)
ajax({
url:config.user.signIn,
data:values,
success:function(result){
if(result.isSuccess){
_this.props.loginSuccess(result.userName, true)
}else {
message.error(`登录失败: ${result.message}, 请联系管理员`)
}
} else {
message.error(`登录失败: ${res.body.message}, 请联系管理员`)
},
complete:function(){
_this.setState({ loading: false })
}
})
})