vue(2)

server/2024/10/18 18:25:50/

总结:

4,知识点总结

  1. 跨域问题
  1. vue搭建管理系统
  1. element-ui入门
  1. axios的基本使用

跨域:

为什么会出现跨域问题?什么是跨域?SSM/SM如何设置跨域

https://zhuanlan.zhihu.com/p/145837536

跨域 问题 原理以及解决方法_前端跨域产生的原因和解决方法-CSDN博客

什么是跨域? 出现原因及解决方法-CSDN博客

跨域原因:

 出于浏览器的同源策略限制。同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)。

什么是跨域:

 当一个请求url协议、域名、端口三者之间任意一个与当前页面url不同即为跨域   

    http://localhost:8088/    前端访问地址

  http://localhost:8888/    后端服务地址

    出现:CORS policy: No 'Access-Control-Allow-Origin'   错误

SM(sprinboot mybatis)如何解决跨域:

解决跨域两种方式:  jsonp      CORS

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

跨域资源共享( CORS(Cross Origin Resource Sharing) ) 是一种基于HTTP标头的机制,它允许服务器指示除其自身之外的任何来源(域、方案或端口),浏览器应允许从中加载资源。每一个页面需要返回一个名为Access-Control-Allow-Origin的http头来允许外域的站点访问,你可以仅仅暴露有限的资源和有限的外域站点访问。

解决方案(springboot 如何使用CORS技术解决跨域):

CORS support in Spring Framework

官网补充:

spring 中对 CORS 规则的校验,都是通过委托给 DefaultCorsProcessor实现的。

DefaultCorsProcessor 处理过程如下:

1,判断依据是 Header中是否包含 Origin。如果包含则说明为 CORS请求,转到 2;否则,说明不是 CORS 请求,不作任何处理。

2,判断 response 的 Header 是否已经包含 Access-Control-Allow-Origin,如果包含,证明已经被处理过了, 转到 3,否则不再处理。

3,判断是否同源,如果是则转交给负责该请求的类处理

4,是否配置了 CORS 规则,如果没有配置,且是预检请求,则拒绝该请求,如果没有配置,且不是预检请求,则交给负责该请求的类处理。如果配置了,则对该请求进行校验。

package com.aaa.sbm.congfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration  //cors-config.xml   <beans>
public class CorsConfig  implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {//链式编程registry.addMapping("/**") //允许那些url请求跨域  /**代表所有请求//.allowedOrigins("http://localhost:8088/","http://localhost:8080/","https://192.168.31.174:7777/")  //允许该域跨域  可以配置多个//.allowedOrigins("*") //* 统配所有域.allowedOriginPatterns("*") //允许域的请求的路径    *统配所有域//.allowedMethods("GET","POST","PUT","DELETE","OPTIONS") //允许请求方法类型.allowedMethods("*") // * 代表所有请求方法类型都可以//.allowedHeaders("header1", "header2", "header3","access-token") //跨域时,允许header头部携带哪些参数  例如header1 .....allowedHeaders("*") // 跨域时,允许header头部携带任何参数.allowCredentials(true) //跨域请求时,是否允许携带并处理cookie(前后端不分离时,使用cookie存储sessionid) ,如果写成true上面allowedOrigins不可以使用*.maxAge(3600);//预检请求检测间隔时长   在对某一个域  http://localhost:8088/ 进行一次预检成功后,该预检会被缓存,接下来的1小时,都不再发options请求//几乎所有的ajax异步请求,除了get  几乎其他所有的方式都会先发一个options请求,测试是否可以正常访问资源(跨域) 如果请求成功,再发真实请求}
}

跨域成功responseHeader中信息:

其他解决方法:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/*** @author: hy* @create: 2023-11-27 19:41:56*/
@Configuration
public class MyCorsConfiguration {@Beanpublic FilterRegistrationBean corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);//config.addAllowedOrigin("http://127.0.0.1:5500");//config.addAllowedOrigin("http://localhost:5500");config.addAllowedOriginPattern("*");config.addAllowedHeader("*");config.addAllowedMethod("*");source.registerCorsConfiguration("/**", config);FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));bean.setOrder(0);return bean;}
}

前端测试代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><script>window.onload=function(){// var xhr = new XMLHttpRequest();// xhr.onreadystatechange=function(){//     if(xhr.status==200 && xhr.readyState==4){//         console.log(xhr.responseText);//     }// }// xhr.open("GET","http://localhost:8080/book/list");// xhr.send();fetch("http://localhost:8080/book/list",{method:"get"}).then(function(resp){console.log(resp);if(resp.ok){return resp.json()}}).then(function(res){console.log(res.data);})}</script>
</body>

后台代码:

@RestController
@RequestMapping("/book")
public class BookController extends BaseController {@Autowiredprivate IBookService bookService;@GetMapping("/list")public Result list(){List<Book> bookList = bookService.list();return  success(bookList);}
}

3.2 管理系统搭建

axios简介和安装:

安装、配置:

安装:

npm install --save axios

配置:引入

import axios from 'axios'

设置路径的默认前缀

axios.defaults.baseURL="http://localhost:8080"

把axios挂载到vue对象

Vue.prototype.$http=axios;

常用请求:

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

看不懂的话、这边也有其他博主的

axios基本用法 - 简书

用法:

那么开始:

发送一个GET请求
javascript">//通过给定的ID来发送请求
axios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(error){console.log(error);});
//以上请求也可以通过这种方式来发送
axios.get('/user',{params:{ID:12345}
})
.then(function(response){console.log(response);
})
.catch(function(error){console.log(error);
});
发送一个POST请求
axios.post('/user',{firstName:'Fred',lastName:'Flintstone'
})
.then(function(res){console.log(res);
})
.catch(function(error){console.log(error);
});一次性并发多个请求
function getUserAccount(){return axios.get('/user/12345');
}
function getUserPermissions(){return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){//当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果}))

axios可以通过配置(config)来发送请求
javascript">//发送一个`POST`请求
axios({method:"POST",url:'/user/12345',data:{firstName:"Fred",lastName:"Flintstone"}
});
创建一个axios实例,并且可以自定义其配置
javascript">var instance = axios.create({baseURL:"https://some-domain.com/api/",timeout:1000,headers: {'X-Custom-Header':'foobar'}
});
求返回的内容:
javascript">{data:{},status:200,//从服务器返回的http状态文本statusText:'OK',//响应头信息headers: {},//`config`是在请求的时候的一些配置信息config: {}
}你可以这样来获取响应信息
axios.get('/user/12345').then(function(res){console.log(res.data);console.log(res.status);console.log(res.statusText);console.log(res.headers);console.log(res.config);})

3.4 前端代码结构

util/AxiosUtil.js:
javascript">//导入axios模块
import axios from 'axios'
//配置axios请求的基础地址
let axiosUtil = axios.create({baseURL:"http://localhost:8081/api"
})
//导出模块对象
export default axiosUtil;
service/UserService.js
import axiosUtil from "../util/AxiosUtil";
//定义用户业务//用户登录
function login(loginUser){//Promise对象return axiosUtil.get("/users/login",{params:{...loginUser}})
}//导出业务类对象
export default {login
}
views/Login.vue
javascript"><template><div><table border="1"><tr><td>用户名</td><td><input type="text" v-model="loginUser.userName"/></td></tr><tr><td>密码</td><td><input type="text" v-model="loginUser.password"/></td></tr><tr><td></td><td><input type="button" value="登录" @click="login"/></td></tr></table></div>
</template>
<script>
//导入用户业务模块
import userService from '../service/UserService'
//导入本组件对象
export default {data(){//数据属性return {loginUser:{userName:"",password:""}}},methods:{ //方法login(){alert(this.loginUser.userName+" "+this.loginUser.password);userService.login(this.loginUser).then(resp=>{console.log(resp.data);let res = resp.data;if(res.code==0 && res.data!=null){//进行路由跳转console.log(this);console.log(this);this.$router.push({name:"MainHome"});}})}}
}
</script>
<style scoped>table{margin:0px auto;}
</style>
router/idnex.js
javascript">import Vue from 'vue'
import VueRouter from 'vue-router'
//饿汉模式,导入登录组件
import Login from '../views/Login.vue'Vue.use(VueRouter)//路由规则const routes = [{path: '/',name: 'Login',component: Login,},{path: '/main',name: 'Main',component: ()=>import("../views/Main.vue"),  //懒汉模式导入组件children:[{path: "",name: 'MainHome',components:{ //配置当前页面上的视图组件default:()=>import("../views/Menu.vue"), //默认视图窗口main:()=>import("../views/MainHome.vue") //主视图窗口}},{path: "goodsList",name: 'GoodsList',components:{ //配置当前页面上的视图组件default:()=>import("../views/Menu.vue"), //默认视图窗口main:()=>import("../views/GoodsList.vue") //主视图窗口}},{path: "goodsAdd",name: 'GoodsAdd',components:{ //配置当前页面上的视图组件default:()=>import("../views/Menu.vue"), //默认视图窗口main:()=>import("../views/GoodsAdd.vue") //主视图窗口}},{path: "goodsUpdate/:goodsId", //:goodsId:配置传入页面的参数name: 'GoodsUpdate',components:{ //配置当前页面上的视图组件default:()=>import("../views/Menu.vue"), //默认视图窗口main:()=>import("../views/GoodsUpdate.vue") //主视图窗口}}]}
]const router = new VueRouter({routes
})export default router

src/App.vue
javascript"><template><div id="app"><router-view/></div>
</template><style>
*{margin:0px;padding:0px;
}
html,body{height: 100%;
}
#app{height: 100%;
}
</style>

3.5 elementui简介和安装

官网:

Element - The world's most popular Vue UI framework

简介:

  Element,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库

安装使用及配置:

npm i element-ui -S

main.js配置:

import ElementUI from 'element-ui';

import 'element-ui/lib/theme-chalk/index.css';

//让Vue引入使用ElementUI

Vue.use(ElementUI)


http://www.ppmy.cn/server/96392.html

相关文章

c++初阶-------模板

作者前言 &#x1f382; ✨✨✨✨✨✨&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f367;&#x1f382; ​&#x1f382; 作者介绍&#xff1a; &#x1f382;&#x1f382; &#x1f382; &#x1f389;&#x1f389;&#x1f389…

Docker常见命令

常见命令 # 启动docker systemctl start docker# 关闭docker systemctl stop docker # 重启docker systemctl restart docker# 查看docker运行状态 systemctl status docker# 设置docker开机启动 systemctl enable docker# 查看docker 版本 docker version# 查看docker守…

Radamsa:一款高性能通用模糊测试工具

关于Radamsa Radamsa是一款高性能的通用模糊测试工具&#xff0c;广大研究人员可以将其当作一个应用程序稳定性测试的测试用例生成工具。 工具运行机制 该工具使用简单&#xff0c;支持自定义脚本开发&#xff0c;可以用于测试程序对格式错误和潜在恶意输入的承受能力。它的工…

科普文:微服务之全文检索ElasticSearch 集成IK分词器

一、IK分词器简介 IKAnalyzer是一个开源的&#xff0c;基于java语言开发的轻量级的中文分词工具包。从2006年12月推出1.0版开始IKAnalyzer已经推出 了3个大版本。最初&#xff0c;它是以开源项目Lucene为应用主体的&#xff0c;结合词典分词和文法分析算法的中文分词组件。新版…

并查集问题

import java.util.HashMap; import java.util.List; import java.util.Stack;public class test33 {//由若干样本a、b、c、d……假设类型为V//在并查集中开始认为每个样本都在单独的集合里//用户可以在任何时候调用如下方法://1.boolean isSameSet(V x ,V y):查询样本x和样本y是…

强软弱虚四大引用

强引用&#xff1a; 如果一个对象具有强引用&#xff0c;垃圾回收器不会回收该对象&#xff0c;当内存空间不足时&#xff0c;JVM 宁愿抛出 OutOfMemoryError异常。 // 强引用 User usernew User();//user就是强引用软引用&#xff1a; 如果一个对象只具有软引用&#xff0…

信息安全专业好吗?

22 届的 211 信安毕业生&#xff0c;目前在读研&#xff08;虽然已经和安全没关系&#xff09;&#xff0c;整体来看大部分高校的信安都是作为计算机的附属专业存在的&#xff0c;除了极具特色的几个高校&#xff0c;例如山大的密码学&#xff0c;广州大学某院士加持的网络安全…

MongoDB 100问

基础问题 1. 什么是MongoDB&#xff1f; MongoDB是一种面向文档的NoSQL数据库&#xff0c;使用BSON&#xff08;二进制JSON&#xff09;格式存储数据。它支持动态模式设计&#xff0c;具有高性能、高可用性和易扩展性。 2. MongoDB和传统关系型数据库的区别是什么&#xff1f…