From 794b642e45307191aad7748286e460d2b7563b45 Mon Sep 17 00:00:00 2001 From: fanxb Date: Thu, 27 Jun 2019 11:32:03 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Feat:=20=E5=89=8D=E7=AB=AF=E6=A1=86?= =?UTF-8?q?=E6=9E=B6=E6=90=AD=E5=BB=BA=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 4 +- src/App.jsx | 26 ++--- src/index.jsx | 6 -- src/pages/Main.jsx | 9 ++ src/pages/main.module.less | 0 src/pages/main/index.jsx | 33 ------ src/pages/public/Login/index.jsx | 21 ++-- src/pages/public/notFound/NotFound.jsx | 17 ++++ src/redux/reducer/loginInfo.js | 23 ++++- src/serviceWorker.js | 135 ------------------------- src/util/httpUtil.js | 36 +++++++ yarn.lock | 24 ++++- 12 files changed, 130 insertions(+), 204 deletions(-) create mode 100644 src/pages/Main.jsx create mode 100644 src/pages/main.module.less delete mode 100644 src/pages/main/index.jsx create mode 100644 src/pages/public/notFound/NotFound.jsx delete mode 100644 src/serviceWorker.js create mode 100644 src/util/httpUtil.js diff --git a/package.json b/package.json index b3a23cc..fb7abb8 100644 --- a/package.json +++ b/package.json @@ -3,8 +3,10 @@ "version": "0.1.0", "private": true, "homepage": ".", + "proxy": "http://ali.tapme.top:8081/mock/16/chat/api/", "dependencies": { "antd": "^3.19.8", + "axios": "^0.19.0", "babel-plugin-import": "^1.12.0", "customize-cra": "^0.2.14", "less": "^3.9.0", @@ -40,4 +42,4 @@ "devDependencies": { "less-loader": "^5.0.0" } -} +} \ No newline at end of file diff --git a/src/App.jsx b/src/App.jsx index 822e736..7116ef4 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,27 +1,16 @@ import React, { Component } from "react"; -import { Route } from "react-router-dom"; +import { Route, Switch, Redirect } from "react-router-dom"; import { withRouter } from "react-router-dom"; import { Provider } from "react-redux"; import store from "./redux"; import Login from "./pages/public/Login"; -import Main from "./pages/main"; +import Main from "./pages/Main"; +import NotFound from "./pages/public/notFound/NotFound"; class App extends Component { constructor(props) { super(props); this.state = {}; - this.checkRoute(this.props.location.pathname); - } - - componentWillReceiveProps(nextProps) { - this.checkRoute(nextProps.location.pathname); - } - - checkRoute(currentPath) { - // if (currentPath !== "/login") { - // console.log("不在登录页,跳转到登录页去"); - // this.props.history.replace("/login"); - // } } render() { @@ -31,8 +20,13 @@ class App extends Component { return (
- - + + + + + {/* 当前面的路由都匹配不到时就会重定向到/404 */} + +
); diff --git a/src/index.jsx b/src/index.jsx index 5775421..77f7bb1 100644 --- a/src/index.jsx +++ b/src/index.jsx @@ -3,7 +3,6 @@ import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import { BrowserRouter } from "react-router-dom"; -import * as serviceWorker from "./serviceWorker"; const s = ( @@ -12,8 +11,3 @@ const s = ( ); ReactDOM.render(s, document.getElementById("root")); - -// If you want your app to work offline and load faster, you can change -// unregister() to register() below. Note this comes with some pitfalls. -// Learn more about service workers: https://bit.ly/CRA-PWA -serviceWorker.unregister(); diff --git a/src/pages/Main.jsx b/src/pages/Main.jsx new file mode 100644 index 0000000..eb3f02d --- /dev/null +++ b/src/pages/Main.jsx @@ -0,0 +1,9 @@ +import React from "react"; + +class Main extends React.Component { + render() { + return
这是主页
; + } +} + +export default Main; diff --git a/src/pages/main.module.less b/src/pages/main.module.less new file mode 100644 index 0000000..e69de29 diff --git a/src/pages/main/index.jsx b/src/pages/main/index.jsx deleted file mode 100644 index 9726411..0000000 --- a/src/pages/main/index.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import React from "react"; -import { connect } from "react-redux"; - -function mapStateToProps(state) { - return { - loginInfo: state.loginInfo - }; -} - -function mapDispatchToProps(dispatch) { - return {}; -} - -class Main extends React.Component { - constructor(props) { - console.log(props); - super(props); - this.state = {}; - } - - render() { - const { token, userInfo } = this.props.loginInfo; - if (token == null) { - return
这是首页,你还没登陆
; - } - return
你好:{userInfo.name}
; - } -} - -export default connect( - mapStateToProps, - mapDispatchToProps -)(Main); diff --git a/src/pages/public/Login/index.jsx b/src/pages/public/Login/index.jsx index 9ba5440..89d49a9 100644 --- a/src/pages/public/Login/index.jsx +++ b/src/pages/public/Login/index.jsx @@ -1,10 +1,10 @@ import React, { Component } from "react"; -import { Button, Input } from "antd"; +import { Button, Input, message } from "antd"; import IconFont from "../../../components/IconFont"; import styles from "./index.module.less"; import { connect } from "react-redux"; -import { Link } from "react-router-dom"; import { changeLoginInfo } from "../../../redux/action/LoginInfoAction"; +import axios from "../../../util/httpUtil"; function mapStateToProps(state) { return {}; @@ -12,7 +12,7 @@ function mapStateToProps(state) { function mapDispatchToProps(dispatch) { return { - dealClick: () => dispatch(changeLoginInfo("12345", { name: "fanxb", age: "12" })) + updateLoginInfo: (token, userInfo) => dispatch(changeLoginInfo(token, userInfo)) }; } @@ -32,8 +32,16 @@ class Login extends Component { this.setState({ password: e.target.value }); }; - login = () => { - console.log("登陆了"); + submit = () => { + axios.post("/public/login", this.state).then(res => { + localStorage.setItem("token", res.token); + localStorage.setItem("userInfo", JSON.stringify(res.userInfo)); + window.token = res.token; + window.userInfo = res.userInfo; + message.success("登录成功"); + this.props.updateLoginInfo(res.token, res.userInfo); + this.props.history.replace("/"); + }); }; render() { @@ -59,10 +67,9 @@ class Login extends Component { - - 回到首页 diff --git a/src/pages/public/notFound/NotFound.jsx b/src/pages/public/notFound/NotFound.jsx new file mode 100644 index 0000000..05af642 --- /dev/null +++ b/src/pages/public/notFound/NotFound.jsx @@ -0,0 +1,17 @@ +import React from "react"; +import { Link } from "react-router-dom"; + +const style = { + "text-align": "center", + "padding-top": "200px" +}; + +const render = () => { + return ( +
+ 404 您的页面走丢啦! 返回首页 +
+ ); +}; + +export default render; diff --git a/src/redux/reducer/loginInfo.js b/src/redux/reducer/loginInfo.js index 5b11848..e8f35bc 100644 --- a/src/redux/reducer/loginInfo.js +++ b/src/redux/reducer/loginInfo.js @@ -1,11 +1,24 @@ import * as loginAction from "../action/LoginInfoAction"; -const initData = { - token: null, - userInfo: null -}; +function getInitData() { + let token, userInfo; + try { + token = localStorage.getItem("token"); + userInfo = JSON.parse(localStorage.getItem("userInfo")); + } catch (e) { + console.error(e); + token = null; + userInfo = null; + } + window.token = token; + window.userInfo = userInfo; + return { + token, + userInfo + }; +} -const LoginStatusReducer = (state = initData, action) => { +const LoginStatusReducer = (state = getInitData(), action) => { switch (action.type) { case loginAction.CHANGE_LOGIN_INFO: return { ...action.data }; diff --git a/src/serviceWorker.js b/src/serviceWorker.js deleted file mode 100644 index f8c7e50..0000000 --- a/src/serviceWorker.js +++ /dev/null @@ -1,135 +0,0 @@ -// This optional code is used to register a service worker. -// register() is not called by default. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on subsequent visits to a page, after all the -// existing tabs open on the page have been closed, since previously cached -// resources are updated in the background. - -// To learn more about the benefits of this model and instructions on how to -// opt-in, read https://bit.ly/CRA-PWA - -const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -export function register(config) { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebook/create-react-app/issues/2374 - return; - } - - window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log( - 'This web app is being served cache-first by a service ' + - 'worker. To learn more, visit https://bit.ly/CRA-PWA' - ); - }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } -} - -function registerValidSW(swUrl, config) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated precached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all ' + - 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' - ); - - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); -} - -function checkValidServiceWorker(swUrl, config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); -} - -export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); - } -} diff --git a/src/util/httpUtil.js b/src/util/httpUtil.js new file mode 100644 index 0000000..b3840e0 --- /dev/null +++ b/src/util/httpUtil.js @@ -0,0 +1,36 @@ +import { notification } from "antd"; +import axios from "axios"; + +//定义http实例 +const instance = axios.create({ + // baseURL: "http://ali.tapme.top:8081/mock/16/chat/api/", + headers: { + token: window.token + } +}); + +//实例添加拦截器 +instance.interceptors.response.use( + function(res) { + return res.data; + }, + function(error) { + console.log(error); + let message, description; + if (error.response === undefined) { + message = "出问题啦"; + description = "你的网络有问题"; + } else { + message = "出问题啦:" + error.response.status; + description = JSON.stringify(error.response.data); + } + notification.open({ + message, + description, + duration: 2 + }); + return Promise.reject(error); + } +); + +export default instance; diff --git a/yarn.lock b/yarn.lock index 90f21f0..51df87a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1945,6 +1945,14 @@ aws4@^1.8.0: resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.8.0.tgz#f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f" integrity sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ== +axios@^0.19.0: + version "0.19.0" + resolved "https://registry.yarnpkg.com/axios/-/axios-0.19.0.tgz#8e09bff3d9122e133f7b8101c8fbdd00ed3d2ab8" + integrity sha512-1uvKqKQta3KBxIz14F2v06AEHZ/dIoeKfbTRkK1E5oqjDnuEerLmYTgJB5AiQZHJcljpg1TuRzdjDR06qNk0DQ== + dependencies: + follow-redirects "1.5.10" + is-buffer "^2.0.2" + axobject-query@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-2.0.2.tgz#ea187abe5b9002b377f925d8bf7d1c561adf38f9" @@ -3247,6 +3255,13 @@ debug@2.6.9, debug@^2.2.0, debug@^2.3.3, debug@^2.6.0, debug@^2.6.8, debug@^2.6. dependencies: ms "2.0.0" +debug@=3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" + integrity sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g== + dependencies: + ms "2.0.0" + debug@^3.2.5, debug@^3.2.6: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" @@ -4266,6 +4281,13 @@ flush-write-stream@^1.0.0: inherits "^2.0.3" readable-stream "^2.3.6" +follow-redirects@1.5.10: + version "1.5.10" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.5.10.tgz#7b7a9f9aea2fdff36786a94ff643ed07f4ff5e2a" + integrity sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ== + dependencies: + debug "=3.1.0" + follow-redirects@^1.0.0: version "1.7.0" resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.7.0.tgz#489ebc198dc0e7f64167bd23b03c4c19b5784c76" @@ -5150,7 +5172,7 @@ is-buffer@^1.0.2, is-buffer@^1.1.5: resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== -is-buffer@^2.0.0: +is-buffer@^2.0.0, is-buffer@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.3.tgz#4ecf3fcf749cbd1e472689e109ac66261a25e725" integrity sha512-U15Q7MXTuZlrbymiz95PJpZxu8IlipAp4dtS3wOdgPXx3mqBnslrWU14kxfHB+Py/+2PVKSr37dMAgM2A4uArw==