06-vue-cli -axios module and domain proxy

1. Introduction to vue-axios

        Vue.js version 2.0 recommends using axios to complete ajax requests.

        Axios is a Promise-based HTTP library that can be used in browsers and node.js

1.1 New features

Create XMLHttpRequests from the browser

Create http request from node.js

Intercept requests and responses

Transform request data and response data

cancel request

Automatically convert JSON data

1.2. Installation

The first one: import

The second: use npm:

        npm install axios

1.3. vue-axios-get request

  1. Introduced in main.js and set global variables
// 导入axios的模块
import axios from 'axios'

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

2. vue-axios-get request syntax

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

3. vue-axios-get request implementation

<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 request

1. Introduce in main.js and set global variables

// 导入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 request, two ways of writing

The first

<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>

the second

2. vue-cli domain name agent

1. What is a proxy

        The English full name of proxy server is Proxy Server, and its function is to act as an agent for network users to obtain network information. To put it vividly: it is a transfer station for network information. Can

        A simple and crude understanding is to convert your domain name into the domain name you visit, form the same source, and you can access it.

2. Why use a proxy

        The separate development of the front and back ends is bound to be inseparable from the solution of cross-domain problems. Proxy is a way for the front-end to solve cross-domain problems.

3. What is cross-domain

        When any of the protocol, domain name, and port of a request url is different from the current url, it is cross-domain

  1. Current page url Whether the requested page url is cross-domain reason http://www.test.com/         
  2. http://www.test.com/index.html No Same source (same protocol, domain name, port number) http://www.test.com/         
  3. https://www.test.com/index.html Different cross-domain protocols (http/https)
  4. http://www.test.com/ http://www.baidu.com/ The cross-domain primary domain name is different (test/baidu) http://www.test.com/
  5. http://blog.test.com/ different cross-domain subdomains (www/blog)

4. Non-homologous restriction

[1] Unable to read cookies from non-same-origin web pages

[2] Unable to access the DOM of non-same-origin web pages

[3] AJAX requests cannot be sent to non-same-origin addresses

5. How to solve cross-domain problems

5.1. The first type: Solve on the server side

Configure as follows

.springboot cross-domain configuration

The following is the cross-domain configuration class of springboot, the springboot version must be a version before 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 The second method: use the front-end solution

Proceed as follows:

1: In the index.js file under the config directory, add the configuration at the 13th line of code proxyTable, the code is as follows:

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

可以配置多个域名代理

2 Set the global configuration of axios in main.js

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 After configuring the above two steps, the project can be written in the following way:

1. New testAjax.vue

2. Introduce the testAjax component in index.js under src/router

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
    },
  ]
})

One: code implementation

1. Front end

post request: test03 | get request: 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. Backend

Create a spring boot project

1. pom follows the initialized 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. Create a controller package and create a new TestAjaxController.java, write the corresponding interface

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";
    }

}

Guess you like

Origin blog.csdn.net/weixin_46048259/article/details/127461893