vue(2)

总结:

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 {
    @Override
    public 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 {
    @Bean
    public 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 {
    @Autowired
    private 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请求
//通过给定的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)来发送请求
//发送一个`POST`请求
axios({
    method:"POST",
    url:'/user/12345',
    data:{
        firstName:"Fred",
        lastName:"Flintstone"
    }
});
创建一个axios实例,并且可以自定义其配置
var instance = axios.create({
  baseURL:"https://some-domain.com/api/",
  timeout:1000,
  headers: {'X-Custom-Header':'foobar'}
});

求返回的内容:
{
  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:
//导入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
<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
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
<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)

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值