06-vue-cli -axios模块和域名代理

1.vue-axios 介绍

        Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

        Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中

1.1新特性

从浏览器中创建 XMLHttpRequests

从 node.js 创建 http 请求

拦截请求和响应

转换请求数据和响应数据

取消请求

自动转换 JSON 数据

1.2.安装

第一种: 引入

第二种: 使用 npm:

        npm install axios

1.3.vue-axios-get请求

  1. 在main.js中引入,并设置全局变量
// 导入axios的模块
import axios from 'axios'

    
//设置axios的全局变量
Vue.prototype.$http=axios;

2.vue-axios-get请求语法

axios.get("请求地址",{ 
    params:”请求参数对象” 
    }).then(function(rs){ //成功返回函数 
    console.log(rs) 
    }) 

3.vue-axios-get请求 实现

<template>
  <div>
    <button type="button" @click="test02">跨域请求演示</button>
  </div>
</template>

<script>
    export default{
    name:"testAjax",
    methods: {
        test02(){//get请求
              this.$http.get(
                    "/testAjax/test01",
                    {params:{"name" : "rock"}}
              ).then(function(rs){
                console.log(rs);
              }).catch(function(rs){
                console.log("服务器连接错误");
              })
    
       },
     }
  }
</script>

<style>
</style>

1.4 vue-axios-post请求

1.在main.js中引入,并设置全局变量

// 导入axios的模块
import axios from 'axios'
//导入qs模块
import qs from 'qs'

//设置axios的全局变量
Vue.prototype.$http=axios;

//设置qs的全局变量
Vue.prototype.$qs = qs;

Vue.config.productionTip = false

2.vue-axios-get请求,两种写法

第一种

<template>
  <div>
    <button type="button" @click="test03">跨域请求演示</button>
  </div>
</template>

<script>
    export default{
    name:"testAjax",
    methods: {
         test03(){//post请求
          this.$http.post(
                "/testAjax/test02",
                this.$qs.stringify({"name" : "rock"})
          ).then(function(rs){
            console.log(rs);
          }).catch(function(rs){
            console.log("服务器连接错误");
          })
      },
     }
  }
</script>

<style>
</style>

第二种

2.vue-cli 域名代理

1.什么是代理

        代理服务器英文全称是Proxy Server,其功能就是代理网络用户去取得网络信息。形象的说:它是网络信息的中转站。可以

        简单粗暴理解为把你的域名转换成你访问的域名,形成同源,就能访问。

2.为什么要用代理

        前后端分离开发,必然离不开跨域问题的解决,代理就是前端解决跨域问题的一种方式

3.什么是跨域

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

  1. 当前页面url 被请求页面url 是否跨域 原因 http://www.test.com/         
  2. http://www.test.com/index.html 否 同源(协议、域名、端口号相同) http://www.test.com/         
  3. https://www.test.com/index.html 跨域 协议不同(http/https)
  4. http://www.test.com/ http://www.baidu.com/ 跨域 主域名不同(test/baidu) http://www.test.com/
  5. http://blog.test.com/ 跨域 子域名不同(www/blog)

4.非同源限制

【1】无法读取非同源网页的 Cookie

【2】无法接触非同源网页的 DOM

【3】无法向非同源地址发送 AJAX 请求

5.如何解决跨域问题

5.1.第一种: 在服务端解决

如下配置

.springboot跨域配置

下面是springboot的跨域配置类,springboot版本 必须是 2.4 以前的版本

package com.hqyj.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CrossConfig implements WebMvcConfigurer {

    @Override public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")/*所有的当前站点的请求地址,都支持跨域访问*/
                .allowedOrigins("*")/*所有的外部域都可跨域访问*/
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")/*哪些请求 需要跨 域配置*/
                .allowCredentials(true) /*是否支持跨域用户凭证*/
                .maxAge(300)/*超时时长设置为5分钟。 时间单位是秒。*/
                .allowedHeaders("*");/*请求体的头部*/ }
}

5.2 第二种: 用前端解决

步骤如下:

1 :在config目录下index.js文件中,在第13行代码 proxyTable处,添加 配置,代码如下:

assetsPublicPath: '/',
      proxyTable: { //设置域名代理
        "/exam":{
          target:"http://localhost:8080",//代理服务器地址
          secure:false,//如果是https接口,需要配置这个参数值为 true
          ws: true,//是否代理websockets
          changeOrigin: true,//允许跨域访问 后端地址
          pathRewrite: {'^/exam': ''} ,
          }
      },

可以配置多个域名代理

2 在 main.js中设置axios的全局配置

import Vue from 'vue'
import App from './App'
import router from './router'
// 导入axios的模块
import axios from 'axios'
//导入qs模块
import qs from 'qs'

//设置axios模块默认的url代理的服务器
axios.defaults.baseURL = '/exam'

//设置session的跨域配置
axios.defaults.withCredentials=true

//设置axios的全局变量
Vue.prototype.$http=axios;

//设置qs的全局变量
Vue.prototype.$qs = qs;

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

3 配置上面两步后,以后在项目可以用下面方式来写:

1.新建testAjax.vue

2.在src/router下的index.js中引入testAjax组件

import Vue from 'vue'
import Router from 'vue-router'
/*  配置地址,叫组件
    第一种:导入hello组件
*/
// import hello from '../components/demo/hello.vue'

/*
    第二种:导入hello组件
*/
import hello from  '@/components/demo/hello'

/*  配置地址,叫组件
    第一种:导入hello01组件
*/
import hello01 from '../components/demo/hello01.vue'

import testAjax from '../components/demo/testAjax.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      /* 斜杠:代表项目的默认地址 */
      path: '/',
      name: 'hello',  /* 组件名称:保持名称唯一性 */
      component: hello  /*  引入组件的别名   */
    },
    {
      path: '/hello01',
      name: 'hello01',
      component: hello01
    },
    {
      path: '/testAjax',
      name: 'testAjax',
      component: testAjax
    },
  ]
})

一:代码实现

1.前端

post请求 :test03 | get请求 :test01 test02

<template>
  <div>
    <button type="button" @click="test01">跨域请求演示</button>
    <button type="button" @click="test02">跨域请求演示</button>
      <button type="button" @click="test03">跨域请求演示</button>
  </div>
</template>

<script>

  export default{
    name:"testAjax",
    methods: {
      test01() {   //跨域请求演示
        $.ajax({
          url: "/exam/testAjax/test01",
          type: "get",
          data:
          {
            "name" : "rock"
          },
          success: function(rs){
            console.log(rs);
          },
          error: function(rs){
            console.log("服务器连接错误");
          }
        })
      },
      test02(){//get请求
          this.$http.get(
                "/testAjax/test01",
                {params:{"name" : "rock"}}
          ).then(function(rs){
            console.log(rs);
          }).catch(function(rs){
            console.log("服务器连接错误");
          })

      },
      test03(){//post请求
          this.$http.post(
                "/testAjax/test02",
                this.$qs.stringify({"name" : "rock"})
          ).then(function(rs){
            console.log(rs);
          }).catch(function(rs){
            console.log("服务器连接错误");
          })
      },
    }
  }
</script>

<style>
</style>

2.后端

创建一个spring boot项目

1.pom遵从初始化的pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hqyj</groupId>
    <artifactId>idea_vue</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>idea_vue</name>
    <description>Demo project for Idea Vue</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.创建controller包并新建TestAjaxController.java,写对应的接口

package com.hqyj.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/testAjax")
public class TestAjaxController {


    @GetMapping("/test01")
    public String test01(String name){
        System.out.println("name="+name);
        return "hello";
    }

    @PostMapping("/test02")
    public String test02(String name){
        System.out.println("name="+name);
        return "hello";
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_46048259/article/details/127461893