The way to send Ajax requests in Vue, axios and its solution to cross-domain problems, the configuration and principle of the proxy mechanism

Ajax requests in Vue

The more popular development method now is asynchronous calling. The front and backends exchange data in the form of asynchronous Ajax requests. The transmitted data uses JSON.

  • After the Ajax request is sent, when the browser receives the response content from the server, it will not reload the entire page, but will only update part of the web page to achieve a partial refresh effect.

Common ways to send AJAX asynchronous requests include

  • Use browser built-in JS objectsXMLHttpRequest
  • Use the browser's built-in JS function fetch such asfetch(‘url’, {method : ‘GET’}).then().then()
  • Third-party library method: Encapsulate XMLHttpRequest, such as the$.get()/post() method provided by jQuery, and the Promise-based HTTP library axiosaxios.get().then()

axios

Use vue-cli to install the axios librarynpm i axios, and then use import in the component to import axios import axios from 'axios'

Use the method provided byvue.js to initiate an Ajax request. The parameter of the method is a configuration objectaxios

  • method: Specify the request method
  • url: Specify the requested path
  • params anddata: Specify the parameters of the request, and the parameter is an object

paramssumdataattribute distinction

  • When using the params attribute, whether sending a GET or POST request, the request parameters are spliced ​​to the request address in the format ofname=value&.., and the request parameters are obtained throughrequset对象的API
  • When using the data attribute, only POST requests can be sent, and the parameters are stored in the request body of the request message in the format ofjson. The relevant jar package is required to obtain the request parameters< /span>将请求体中的json数据转成Java对象

Useaxios({配置对象}).then(回调函数) method to initiate Ajax request

  • Useparams属性 to splice the request parameters into the request address in the format ofname=value&name=value
// 导入axios
import axios from 'axios'
testAjax:function (event) {
    
    
    axios({
    
    
        method:"post",
        url:event.target.href,
        params:{
    
    
            username:"admin",
            password:"123456"
        }
    }).then(function (response) {
    
    //服务器处理Ajax请求成功后执行的回调函数
        // 服务器响应的结果都会被封装在response对象中,响应的数据都在data属性中
        alert(response.data);
    });

Use the axios.post(url,[data]).then(回调函数) method and axios.get(url).then(回调函数) method to initiate an Ajax request

  • Usedata属性 to store the request parameters asjson的格式 into the request body of the request message
testAjax(){
    
    
    axios.post(
        "/SpringMVC/test/ajax",
        {
    
    username:"admin",password:"123456"}
    ).then(response=>{
    
    
        console.log(response.data);
    });
},

vue-resource插件

Install the vue-resource plug-innpm i vue-resource, then import the plug-in in the main.js file and use it. At this time, all vm and vc instances in the project will Added$http属性

import Vue from 'vue'
import App from './App.vue'
// 导入插件vue-resource
import vueResource from 'vue-resource'
Vue.config.productionTip = false

// 使用插件,此时项目中所有的vm和vc实例上都添加了$http属性
Vue.use(vueResource)
new Vue({
    
    
  el : '#app',
  render : h => h(App)
})

The usage of sending requests using the vue-resource plug-in is the same as axiosthis.$http.get(‘’).then()

export default {
    
    
    name : 'App',
    data() {
    
    
        return {
    
    
            bugList : []
        }
    },
    // 在mounted钩子中发送ajax请求将响应的数据保存到bugList数组当中
    mounted() {
    
    
        // 使用vue-resource插件来发送AJAX请求
        this.$http.get('/api/vue/bugs').then(
            response => {
    
    
                console.log('响应数据:', response.data)
                this.bugList = response.data
            },
            error => {
    
    
                console.log('错误信息为:', error.message)
            }
        )
    },

Ajax cross-domain issues

Reference articlesAjax cross-domain problems and their solutions

启用Vue脚手架内置服务器

Vue scaffolding内置了一个服务器端口号是8080, the proxy function is not enabled by default

Insert image description here

We need to add configuration to the vue.config.js file to enable the proxy mechanism of vue-cli. After modifying the configuration file, we need to restart the server. At this time, Vue will be inside the server. Generate a small program

// 简单配置不支持配置多个代理
devServer: {
    
    
    // Vue脚手架内置的8080服务器负责代理访问8000服务器,到时候将资源直接拼接到端口后面
    proxy: 'http://localhost:8000' 
}

Advanced configuration: supported配置多个代理

 devServer: {
    
    
    proxy: {
    
    
       // 只代理以'/api'开始的资源(请求路径) 
      '/api': {
    
    
        target: 'http://localhost:8000',
		// URL重写,将路径中的'/api'以''代替,然后再将重写后的请求路径拼接到目标服务器的端口号后面
        pathRewrite: {
    
    '^/api' : ''},
        ws: true,
        changeOrigin: true
      },
      // 只代理以'/abc'开始的资源(请求路径) 
	  '/abc': {
    
    
        target: 'http://localhost:8001',
        pathRewrite: {
    
    '^/abc' : ''},
        // 默认值true,开启对websockt的支持(一种实时推送技术),
        ws: true,
        // 默认值true,改变起源让目标服务器不知道我们真正的起源在哪里,此时目标服务器获取到的是自己端口的起源
        changeOrigin: true
      }
       // 代替以'/'开始的资源即所有资源 
      '/': {
    
    
          
      }  
    }
  }

When sending an AJAX request, it will first look for resources from its own server/vue/bugs (the resource may be a static or dynamic Java program). If it cannot be found, it will go to the proxy server. Find corresponding resources

<script>
    import axios from 'axios'
    export default {
        name : 'Bugs',
        methods: {  
            getBugs(){
                // http://localhost:8080/vue/bugs-->http://localhost:8000/vue/bugs
                /* axios.get('/vue/bugs').then(
                    response => {
                        console.log('服务器响应回来的数据:', response.data)
                    },
                    error => {
                        console.log('错误信息:', error.message)
                    }
                ) */
                
                // 当前按钮这个页面就是在8080服务器上,所以访问当前服务器上的资源时http://localhost:8080可以省略
			   // 先访问本地资源http://localhost:8080/api/vue/bugs---->重写URL删除'/api'(以空字符串代替)-->http://localhost:8000/vue/bugs
                axios.get('/api/vue/bugs').then(
                    response => {
                        console.log('服务器响应回来的数据:', response.data)
                    },
                    error => {
                        console.log('错误信息:', error.message)
                    }
                )
            }
            
            // http://localhost:8080/api/user/bugs-->重写URL删除'/abc'(以空字符串代替)-->http://localhost:8000/vue/users
            getUsers(){
                axios.get('/abc/vue/users').then(
                    response => {
                        console.log('服务器响应回来的数据:', response.data)
                    },
                    error => {
                        console.log('错误信息:', error.message)
                    }
                )
            },
            
        },
    }
</script>

Guess you like

Origin blog.csdn.net/qq_57005976/article/details/134969425