前后端登录
Posted zrh-960906
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前后端登录相关的知识,希望对你有一定的参考价值。
流式布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>流式布局</title> <style> .box { width: 800px; height: 200px; background-color: orange; /*页面宽度缩放,盒子始终居中*/ margin-left: auto; margin-right: auto; /*width: 80%;*/ /*vw: view width | vh: view height*/ /*width: 80vw;*/ /*width: 80vh;*/ } .sup { font-size: 40px; } .sub { /*font-size: inherit;*/ /*font-size: 1.5em;*/ /*width: 5em;*/ font-size: 2rem; } html { font-size: 30px; } </style> </head> <body> <div class="box"></div> <div class="sup"> <div class="sub">字</div> </div> </body> </html>
js函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js函数</title> </head> <body> <h1>js函数</h1> </body> <script> function fn1(a, b, c, d) { console.log(a, b, c, d); console.log(‘fn1 run‘); } fn1(1, 2, 3); let fn2 = function (...args) { console.log(args); console.log(args[0]); console.log(‘fn2 run‘); }; fn2(1, 2, 3, 4); (function () { console.log(‘fn3 run‘); })(); let fn4 = () => { console.log(‘fn4 run‘); }; fn4(); // 有参有反 let fn5 = (a, b) => { console.log(a, b); return a + b; }; let res = fn5(1, 2); console.log(res); // 箭头函数函数体如果只有返回值,可以简写 let fn6 = (a, b) => a + b; res = fn6(10, 20); console.log(res); // 当形参只有一个,可以省略() let fn7 = a => a * 2; res = fn7(10); console.log(res); // 当形参为空的简写方式 let fn8 = () => 200; res = fn8(); console.log(res); </script> </html>
面向对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>面向对象js</title> </head> <body> <h1>面向对象js</h1> </body> <script> class Student { constructor(name) { console.log(‘构造器调用了‘); this.name = name; } study() { console.log(`${this.name}在学习`) } } let s1 = new Student(‘Bob‘); console.log(s1.name); s1.study(); function Teacher(name) { this.name = name; this.teach = function () { console.log(`${this.name}在教学`) }; this.test = () => { console.log(`${this.name}-test`) } } let t1 = new Teacher(‘Tom‘); console.log(t1.name); t1.teach(); t1.test(); // 可以理解为类属性,所有对象共有 Teacher.prototype.age = 10; Teacher.prototype.sleep = function () { console.log(`${this.name}在睡觉`) }; console.log(t1.age); t1.sleep(); let t2 = new Teacher(‘Jerry‘); console.log(t2.age); t2.sleep(); // Vue.prototype.abc = 123; // let localTag = {}; // Vue.component(‘‘,{}); // new Vue({ // components: { // localTag // } // }); // function 与 箭头函数有本质区别 let h1 = document.querySelector(‘h1‘); h1.onclick = function () { alert(this.innerText); console.log(this); }; h1.onclick = () => { alert(this.innerText); console.log(this); } </script> </html>
前后端登录
v-proj 前端
App.vue
<template> <div id="app"> <router-view/> </div> </template> <style> body,ul, h1{ padding: 0; margin: 0; list-style: none; } </style>
views/Login.vue
cnpm install axios
<template> <div class="login"> <h1>登录页面</h1> <hr> <form action=""> <p> <label for="username">账号:</label> <input type="text" id="username" name="username" v-model="username"> </p> <p> <label for="password">密码:</label> <input type="password" id="password" name="password" v-model="password"> </p> <button type="button" @click="login">登录</button> </form> </div> </template> <script> export default { name: "Login.vue", data () { return { username: ‘‘, password: ‘‘, } }, beforeCreate() { // 查看localStorage中是否存在token(是否登录),登录跳转主页 let token = localStorage.token; if (token) { this.$router.push(‘/‘) } }, methods: { login () { let username = this.username; let password = this.password; // console.log(username); // console.log(password); if (!(username && password)) { alert(‘信息有误‘); return false } // console.log(username); this.$axios({ url: ‘http://127.0.0.1:8001/login/‘, method: ‘post‘, params: { username, password }, }).then(response => { // console.log(‘hi‘); // console.log(response); // console.log(response.data.status); let status = response.data.status; if (status === 0) { alert(‘登录成功‘); // 记录登录状态 localStorage.token = response.data.token; localStorage.username = response.data.username; // 跳转主页 this.$router.push(‘/‘); } else { alert(‘登录失败‘) } }).catch(() => { alert(‘登录异常‘) }); // 清空输入框 this.username = ‘‘; this.password = ‘‘; } } } </script> <style scoped> .login { text-align: center; } button { /*display: block;*/ width: 220px; } </style>
views/Home.vue
<template> <div class="home"> <div class="header"> <h1>主页</h1> <span v-if="token"> <b>{{ username }}</b> | <b @click="logout">注销</b> </span> <span v-else> <b>请登录</b> </span> </div> <hr> <div class="ctx"> <p> <button @click="changeInfo(‘/phone/‘)">phone</button> <button @click="changeInfo(‘/tv/‘)">tv</button> </p> <div v-for="info in infos" :key="info.url"> <img width="200" :src="info.url" alt=""> <p>{{ info.title }}</p> </div> </div> </div> </template> <script> export default { name: ‘home‘, data() { return { token: localStorage.token ? localStorage.token : ‘‘, username: localStorage.username ? localStorage.username : ‘‘, infos: [], } }, components: {}, beforeCreate() { // 查看localStorage中是否存在token(是否登录),未登录跳转登录页面 this.$options.methods._checkToken(); }, methods: { logout() { // 丢弃登录状态,就可以完成注销(不需要后台参与) localStorage.clear(); this.token = ‘‘; this.username = ‘‘; }, _checkToken() { let token = localStorage.token; if (!token) { this.$router.push(‘/login‘) } }, changeInfo(path) { this.$axios({ url: `http://127.0.0.1:8001${path}`, method: ‘get‘, headers: { authorization: this.token } }).then(response => { console.log(response.data); this.infos = response.data.results; }) } }, watch: { token() { this._checkToken(); } }, created() { this.$axios({ url: ‘http://127.0.0.1:8001/phone/‘, method: ‘get‘, headers: { authorization: this.token } }).then(response => { console.log(response.data); this.infos = response.data.results; }) } } </script> <style scoped> h1 { float: left; } span { float: right; } .header:after { content: ‘‘; display: block; clear: both; } .header { line-height: 80px; } </style>
router/index.js
import Vue from ‘vue‘ import VueRouter from ‘vue-router‘ import Home from ‘../views/Home.vue‘ import Login from ‘../views/Login.vue‘ Vue.use(VueRouter); const routes = [ { path: ‘/‘, name: ‘home‘, component: Home }, { path: ‘/home‘, redirect: ‘/‘ //路由重定向 }, { path: ‘/login‘, name: ‘login‘, component: Login }, ]; const router = new VueRouter({ mode: ‘history‘, base: process.env.BASE_URL, routes }); export default router
main.js
cnpm install jquery
cnpm install bootstrap@3
import Vue from ‘vue‘ import App from ‘./App.vue‘ import router from ‘./router‘ import store from ‘./store‘ Vue.config.productionTip = false; import axios from ‘axios‘ Vue.prototype.$axios = axios; // 配置bootstrap环境 import ‘bootstrap‘ import ‘bootstrap/dist/css/bootstrap.min.css‘ new Vue({ router, store, render: h => h(App) }).$mount(‘#app‘);
vue.config.js
const webpack = require("webpack"); module.exports = { configureWebpack: { plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", Popper: ["popper.js", "default"] }) ] } };
dg_proj 后端
主路由 urls.py
from django.conf.urls import url from django.contrib import admin from django.views.static import serve from django.conf import settings from app import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/$‘, views.login), url(r‘^tv/$‘, views.tv), url(r‘^phone/$‘, views.phone), url(r‘^media/(?P<path>.*)‘, serve, {‘document_root‘: settings.MEDIA_ROOT}), ]
app.views.py
from django.shortcuts import render from django.http import JsonResponse # Create your views here. def login(request): username = request.GET.get(‘username‘) password = request.GET.get(‘password‘) # 规定账号 abc 密码 123 print(username,password) if username == "abc" and password == "123": return JsonResponse({ ‘status‘: 0, ‘msg‘: ‘登录成功‘, ‘token‘: ‘token.abc.123‘, ‘username‘: username, }) return JsonResponse({ ‘status‘: 1, ‘msg‘: ‘登录失败‘, }) def tv(request): token = request.META.get(‘HTTP_AUTHORIZATION‘) if not token: return JsonResponse({ ‘status‘: 1, ‘msg‘: ‘没有权限‘, },json_dumps_params={‘ensure_ascii‘: False}) return JsonResponse({ ‘status‘: 0, ‘msg‘: ‘ok‘, ‘results‘: [ { ‘url‘: ‘http://127.0.0.1:8001/media/img/003.jpg‘, ‘title‘: ‘电视一号‘ }, { ‘url‘: ‘http://127.0.0.1:8001/media/img/004.jpg‘, ‘title‘: ‘电视二号‘ } ] },json_dumps_params={‘ensure_ascii‘: False}) def phone(request): token = request.META.get(‘HTTP_AUTHORIZATION‘) if not token: return JsonResponse({ ‘status‘: 1, ‘msg‘: ‘没有权限‘ }, json_dumps_params={‘ensure_ascii‘: False}) return JsonResponse({ ‘status‘: 0, ‘msg‘: ‘ok‘, ‘results‘: [ { ‘url‘: ‘http://127.0.0.1:8001/media/img/001.jpg‘, ‘title‘: ‘手机一号‘ }, { ‘url‘: ‘http://127.0.0.1:8001/media/img/002.jpg‘, ‘title‘: ‘手机二号‘ } ] }, json_dumps_params={‘ensure_ascii‘: False})
dg_proj/settings.py
INSTALLED_APPS = [ ‘corsheaders‘ ] MIDDLEWARE = [ ‘corsheaders.middleware.CorsMiddleware‘, ] CORS_ORIGIN_ALLOW_ALL = True LANGUAGE_CODE = ‘zh-hans‘ TIME_ZONE = ‘Asia/Shanghai‘ USE_I18N = True USE_L10N = True USE_TZ = False MEDIA_ROOT = os.path.join(BASE_DIR, ‘media‘)
app/apps.py
from django.apps import AppConfig class AppConfig(AppConfig): name = ‘app‘
以上是关于前后端登录的主要内容,如果未能解决你的问题,请参考以下文章
spring boot2整合shiro安全框架实现前后端分离的JWT token登录验证
vue + spring boot + spring security 前后端分离 携带 Cookie 登录实现 只写了个登录