Vue2 - implement asynchronous request and server proxy configuration

1. Realize ajax asynchronous request

Method 1 uses axios to implement ajax asynchronous requests

Axios is a promise-based network request library that can be used in browsers and node.js

Axios (compared to the native XMLHttpRequest object) is simple and easy to use. (Compared to jQuery) the axios package is small in size and provides an easy-to-extend interface. It is a library focused on network requests.

In the project, install the axios library.

npm i axios

Introduce the axios library in the script tag

import axios from 'axios'

use axios

const url='http://localhost:8080/students';
axios.get(url).then(
          //成功的回掉
          response=>{
            console.log("请求成功了");
            console.log(response);
            console.log(response.data);
          },
          //失败的回调
          error=>{
            console.log("请求失败了",error.message);
            console.log(error);
          }
      )
    

Reference document: http://www.axios-js.com/zh-cn/docs/


Method 2 is implemented using the plugin vue-resource (not recommended)

Install the vue-resource plugin in the project

npm install vue-resource --save-dev

Introduce the plugin library in the main.js file and use the plugin

import Vue from 'vue'
import App from './App.vue'

import vueResource from 'vue-resource'//引入插件

Vue.config.productionTip = false
/  
   使用了插件 vue-resource 后,vc身上会多出来一个属性 $http (默认是没有该属性)
  /
Vue.use(vueResource)//使用插件

new Vue({
  render: h => h(App),
}).$mount('#app')

Note: After using the plug-in vue-resource, there will be an extra attribute $http on vc (the default is no attribute)

Instructions

/  
  用 this.$http.get(url) 代替 axios.get(url)
  用法是一样的
 /
const url='http://localhost:8080/students';
this.$http.get(url).then(
      //成功的回掉
      response=>{
        console.log("请求成功了");
        console.log(response);
        console.log(response.data);
      },
      //失败的回调
      error=>{
        console.log("请求失败了",error.message);
        console.log(error);
      }
  )

The usage is the same as axios, use this.$http.get(url) instead of axios.get(url)

However, the vue-resource library is not maintained frequently, and it is recommended to use axios (the package of axios is better)


Two, Vue scaffolding configuration server proxy (to solve cross-domain problems)

Configure the devServer attribute in vue.config.js, that is, turn on the proxy server, that is, future requests can find the proxy server to get data.

Method 1 (not recommended)

Add the following configuration in vue.config.js:

 devServer:{
  proxy:"http://localhost:5000"
}

illustrate:

Advantages: The configuration is simple, and it can be sent directly to the front end (8080) when requesting resources.

Disadvantages: Multiple proxies cannot be configured, and it is not possible to flexibly control whether requests go through proxies.

Way of working:

When the requested resource is under the front-end server, it will not be forwarded to the (back-end) server through the proxy.

When the requested resource is not available under the current server, the proxy will request data through the devServer.proxy target server address configured in the vue.config.js file, and the target server will return with the proxy, and the proxy will automatically return to the current one.

That is, if the proxy is configured according to the above, when a resource that does not exist in the front end is requested, the request will be forwarded to the server (matching front-end resources first)


Method 2 (recommended)

Write vue.config.js to configure specific proxy rules:

module.exports = {
devServer: {
    proxy: {
    '/api1': {// 匹配所有以 '/api1'开头的请求路径
      target: 'http://localhost:5000',// 代理目标的基础路径
      pathRewrite: {'^/api1': ''},//请求时重写,将前缀目替换为空,解决在目标服务器跳转前缀目录404的问题
     // ws: true,//用于支持websocket ,默认true
       changeOrigin: false 
    },
    '/api2': {// 匹配所有以 '/api2'开头的请求路径
      target: 'http://localhost:5001',// 代理目标的基础路径
      changeOrigin: true,
      pathRewrite: {'^/api2': ''}
    }
  }
}
}
  • changeOrigin is used to control the host value in the request header ==> modify the original path when accessing (default is true), the sender address received by the target server (that is, the host field in the request field): the root address will be modified to be consistent with the target address localhost: 500x, false keeps the sender's server address localhost: 8080.

  • When changeOrigin is set to true, the host in the request header received by the server is: localhost:5000

  • When changeOrigin is set to false, the host in the request header received by the server is: localhost:8080

  • The default value of changeOrigin is true.

illustrate:

Advantages: Multiple proxies can be configured, and it is possible to flexibly control whether requests go through proxies.

Disadvantages: The configuration is slightly cumbersome, and a prefix must be added when requesting resources.

Example:

 // const url='http://localhost:5001/students';//(未开启代理)这里是直接请求目标服务器,会出现跨域问题(可以通过配置代理服务器解决)
      /  
         开启代理后(方法一 测试)
        /
      const url='http://localhost:8080/students';
      axios.get(url).then(
          //成功的回调
          response=>{
            console.log("请求成功了");
            console.log(response);
            console.log(response.data);
          },
          //失败的回调
          error=>{
            console.log("请求失败了",error.message);
            console.log(error);
          }
      )
    },
  • (Configure devServer.proxy in the vue.config.js file (proxy: the address of the target server + port) ==> configure the proxy server through scaffolding)

  • Just request the address to change back to the original address of the scaffolding itself (the address of the proxy server is the same as the address of the project server) ==>

  • Process: get data => get directly to the proxy => when the requested resources are not available under the front-end server, the proxy will request data through the devServer.proxy target server address configured in the vue.config.js file, and the target server will return the proxy. The proxy will automatically return to the current.


Guess you like

Origin blog.csdn.net/weixin_41606115/article/details/129034545